mapstruct 中的条件映射
Conditional maping in mapstruct
我有来自 jackson 的 dto 及其带有 orm hibernate 的更新数据库:
class dto {
string f1;
bool isModifiedF1;
string f2;
bool isModifiedF2;
setF1(str s) {
this.isModifiedF1 = true;
this.f1 = s;
}
setF2(str s) {
this.isModifiedF2 = true;
this.f2 = s;
}
//othre setter like that
}
我喜欢这样的东西:
classMpperImpl {
modify(dto , entity) {
if(dto.isModifedF1){
entity.setF1(dto.getF1);
}
if(dto.isModifedF2){
entity.setF1(dto.getF2);
}
//and other method
}
}
怎么做?
我锁定 soulotion 以与所有领域一起工作,现在我只是忽略我需要的那个重要领域,并使用 @AfterMapping 手动设置它
我需要避免休眠中任何未更改的字段,例如级联创建字段...
谢谢
MapStruct 具有存在检查的概念。参考文档的 Source presence checking 部分中有更多信息。
您实际需要做的是使用类似 hasF1
的方法,MapStruct 将调用该方法。对于您的特定示例,它看起来像:
class Dto {
private string f1;
private boolean isModifiedF1;
private string f2;
private boolean isModifiedF2;
public boolean hasF1() {
return isModifiedF1;
}
public void setF1(str s) {
this.isModifiedF1 = true;
this.f1 = s;
}
public boolean hasF2() {
return isModifiedF2;
}
public void setF2(str s) {
this.isModifiedF2 = true;
this.f2 = s;
}
// Others
}
然后在生成的代码中 MapStruct 会做类似
的事情
class DtoMapperImpl {
public void modify(Dto dto, Entity entity) {
if(dto.hasF1()){
entity.setF1(dto.getF1());
}
if(dto.hasF2()){
entity.setF2(dto.getF2());
}
//and other method
}
我有来自 jackson 的 dto 及其带有 orm hibernate 的更新数据库:
class dto {
string f1;
bool isModifiedF1;
string f2;
bool isModifiedF2;
setF1(str s) {
this.isModifiedF1 = true;
this.f1 = s;
}
setF2(str s) {
this.isModifiedF2 = true;
this.f2 = s;
}
//othre setter like that
}
我喜欢这样的东西:
classMpperImpl {
modify(dto , entity) {
if(dto.isModifedF1){
entity.setF1(dto.getF1);
}
if(dto.isModifedF2){
entity.setF1(dto.getF2);
}
//and other method
}
}
怎么做? 我锁定 soulotion 以与所有领域一起工作,现在我只是忽略我需要的那个重要领域,并使用 @AfterMapping 手动设置它 我需要避免休眠中任何未更改的字段,例如级联创建字段...
谢谢
MapStruct 具有存在检查的概念。参考文档的 Source presence checking 部分中有更多信息。
您实际需要做的是使用类似 hasF1
的方法,MapStruct 将调用该方法。对于您的特定示例,它看起来像:
class Dto {
private string f1;
private boolean isModifiedF1;
private string f2;
private boolean isModifiedF2;
public boolean hasF1() {
return isModifiedF1;
}
public void setF1(str s) {
this.isModifiedF1 = true;
this.f1 = s;
}
public boolean hasF2() {
return isModifiedF2;
}
public void setF2(str s) {
this.isModifiedF2 = true;
this.f2 = s;
}
// Others
}
然后在生成的代码中 MapStruct 会做类似
的事情class DtoMapperImpl {
public void modify(Dto dto, Entity entity) {
if(dto.hasF1()){
entity.setF1(dto.getF1());
}
if(dto.hasF2()){
entity.setF2(dto.getF2());
}
//and other method
}