我有一个由 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;
}
}
我们确实知道这个布尔值永远不应该为空,这是由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/说:
对于布尔属性,我们允许 getter 方法来匹配模式:
public boolean is<PropertyName>();
is 应该用于布尔值(原始类型) 当我们确实想返回对象时,我们使用 getX() 例如布尔值 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;
}