MapStruct
2023-12-17 15:30:20
一、前言
? ? ? ?MapStruct是一个基于注解(jdk6 annotation processor, 例如 lombok)的代码生成框架,用于实现不同对象之间的映射。
二、使用样例
1.用于映射的样例
public class Customer {
private Long id;
private String name;
//getters and setter omitted for brevity
}
public class CustomerDto {
public Long id;
public String customerName;
}
@Mapper
public interface CustomerMapper {
CustomerMapper INSTANCE = Mappers.getMapper( CustomerMapper.class );
@Mapping(source = "customerName", target = "name")
Customer toCustomer(CustomerDto customerDto);
@InheritInverseConfiguration
CustomerDto fromCustomer(Customer customer);
}
2.使用转化器
@Service
public class CustomerService{
@Resource
private CustomerRepository repository;
/**
* 存储顾客
*/
public void saveCustomer(CustomerDto dto){
Customer customer = CustomerMapper.INSTANCE.toCustomer(dto);
repository.save(customer);
}
}
三、高级扩展
1.请求驼峰处理器
a.实现自定义命名插件
将target的setter和getter方法与source的property对应
public class CustomCamelNamingStrategy extends DefaultAccessorNamingStrategy {
@Override
public String getPropertyName(ExecutableElement getterOrSetterMethod) {
String methodName = getterOrSetterMethod.getSimpleName().toString();
if (methodName.contains("-")){
String fieldName = methodName.subString(3);
char []chs = fieldName.toCharArray();
chs[0] = Character.toLowerCase(chs[0]);
return toCamelName(new String(chs));
}
return super.getPropertyName(getterOrSetterMethod);
}
private String toCamelName(String fieldName){
String res = "";
char[] chs = fieldName.toCharArray();
for (int i = 0; i < chs.length; i++){
if(chs[i] == '_'){
res += Character.toUpperCase(chs[++i]);
continue;
}
res+=chs[i];
}
return res;
}
}
b.配置使用
java spi 配置
resources/META-INF.services/org.mapstruct.ap.spi.AccessorNamingStrategy
org.mapstruct.example.spi.CustomCamelNamingStrategy?
文章来源:https://blog.csdn.net/qq_37011724/article/details/135021503
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!