1.pom.xml中引入依赖:
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.3.1.Final</version>
</dependency>
<dependency> //自动生成转换接口的实现类
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.1.Final</version>
<scope>provided</scope>
</dependency>
2.创建一个类型转换接口:
package com.as.test.transfor;
import com.as.test.entity.TbUser;
import com.as.test.entity.entity.UserInvo;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
/**
* @author dhq
* @version 1.0
* @date 2024/4/18 19:16
*/
@Mapper
public interface UserTransfor {
UserTransfor INSTANCE = Mappers.getMapper(UserTransfor.class);
public TbUser userInvoToEntity(UserInvo invo);
}
3.使用方式
@PostMapping("/add2")
public Boolean addUser(@RequestBody UserInvo invo){
//mapstruct的使用
TbUser tbUser = UserTransfor.INSTANCE.userInvoToEntity(invo);
tbUser.setLastLoginTime(LocalDateTime.now());
boolean save = tbUserService.save(tbUser);
Long id = tbUser.getId();
System.out.println("学生id为:"+id);
TbUser user = getUser(id.toString());
System.out.println("学生信息为:"+user);
return save;
}
4.自动生成转化类接口的实现类
代码:
package com.as.test.transfor;
import com.as.test.entity.TbUser;
import com.as.test.entity.entity.UserInvo;
import javax.annotation.Generated;
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2024-04-18T19:52:39+0800",
comments = "version: 1.3.1.Final, compiler: javac, environment: Java 1.8.0_121 (Oracle Corporation)"
)
public class UserTransforImpl implements UserTransfor {
@Override
public TbUser userInvoToEntity(UserInvo invo) {
if ( invo == null ) {
return null;
}
TbUser tbUser = new TbUser();
tbUser.setId( invo.getId() );
tbUser.setIpAddress( invo.getIpAddress() );
tbUser.setLoginType( invo.getLoginType() );
tbUser.setPassword( invo.getPassword() );
tbUser.setPhone( invo.getPhone() );
return tbUser;
}
}
2.位置: