将布尔值更改为布尔值会在 MapStruct 中抛出 noSuchMethodError

Changing Boolean to boolean throws noSuchMethodError in MapStruct

我有一个由 hibernate 定义的布尔值

public class MyClassWithMyVar {

     @Column(name="myVar", nullable=false)
     private Boolean myVar;

     public Boolean getMyVar(){
         return myVar;
     }

     public void setMyVar(Boolean myVar){
         this.myVar=myVar;
     }

}

我们知道这个布尔值永远不应该为 null,mapstruct

在一些映射器中使用了它
@Mapper
@Mappings({@Mapping(target = "id", ignore =true)})
abstract MyClassWithMyVar copyMyClassWithMyVar(MyClassWithMyVar myClassWithMyVar);

然后我将所有具有布尔值的地方更改为布尔值,运行 我的应用程序并抛出 NoSuchMethodError:

org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoSuchMethodError: MyClassWithMyVar.getMyVar()Ljava/lang/Boolean;

mapstruct 遵循 JavaBeans 规范,而 JavaBeans 规范 http://download.oracle.com/otndocs/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/ 说:

for boolean properties, we allow a getter method to match the pattern: public boolean is<PropertyName>();

is 应该用于布尔值(原始类型) 当我们确实想要 return 对象时,我们使用 getX() 例如 Boolean getMyBoolean()。

您可以在 mapstruct 中创建自己的方法。 下面的转换示例

class Entity{
Boolean x;
};
class DTOEntity{
boolean z;
}

在 Mapstruct 中试试这个

@Mapping(target = "z", source = "x", qualifiedByName="getBoolean")
DTOEntity entityToDto(Entity entity);
@Named("getBoolean")
default boolean getBoolean(Boolean x) {
    return  (boolean) x;
}

}