在实际的业务开发过程中,部分类会有类对像成员,但是在DB保存时只是一个段,以一定的字符串形保存,比如以下USER表中work_info以以下形式保存
而实际的User类如下
public class User extends Model<User> {
private Long id;
@TableId(type = IdType.ASSIGN_UUID)
private String specid;
private String name;
private Integer age;
private String email;
private WorkInfo workInfo;
private int deleted;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime createtime;
@Version
private long version;
private String fab;
}
其中workInfo类如下
@Data
public class WorkInfo {
private String title;
private String Company;
private String adrees;
}
这时从DB取数据时就会涉及如何转换成WorkInfo类。
以Mybatis中提供了BaseTypeHandler这个类形式类型自动转换,下面我们看看在mybatis-plus中如何进行?
1.在User类增加相关注解
@Data
@TableName(autoResultMap = true)
public class User extends Model<User> {
private Long id;
@TableId(type = IdType.ASSIGN_UUID)
private String specid;
private String name;
private Integer age;
private String email;
@TableField(value = "work_info",typeHandler = WorkInfoTypeHandler.class)
private WorkInfo workInfo;
private int deleted;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime createtime;
@Version
private long version;
private String fab;
}
2.准备类WorkInfoTypeHandler继承BaseTypeHandler
public class WorkInfoTypeHandler extends BaseTypeHandler<WorkInfo> {
private String ObjectToString(WorkInfo workInfo) throws Exception
{
System.out.println("String ObjectToString");
String s="";
Field[] fields=workInfo.getClass().getDeclaredFields();
System.out.println(fields.length);
for(Field field:fields){
field.setAccessible(true);
if(s.length()>0)
s=s+",";
s+=field.getName()+"="+field.get(workInfo).toString();
}
return s;
}
private WorkInfo StringToObject(String workInfo) {
System.out.println("WorkInfo StringToObject");
String[] objectValues=workInfo.split(",");
WorkInfo workInfo1=new WorkInfo();
Field[] fields=workInfo1.getClass().getDeclaredFields();
for(String objectValue :objectValues) {
String[] filedValue = objectValue.split("=");
for (Field field : fields) {
if (field.getName().equals(filedValue[0])) {
field.setAccessible(true);
try {
field.set(workInfo1, filedValue[1]);
} catch (IllegalAccessException e) {
e.printStackTrace();
try {
field.set(workInfo1, null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
return workInfo1;
}
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, WorkInfo workInfo, JdbcType jdbcType) throws SQLException {
System.out.println("setNonNullParameter");
try {
preparedStatement.setString(i, this.ObjectToString(workInfo));
} catch (Exception exception){
exception.printStackTrace();
}
}
@Override
public WorkInfo getNullableResult(ResultSet resultSet, String s) throws SQLException {
System.out.println("getNullableResult String s ");
WorkInfo workInfo=this.StringToObject(resultSet.getString(s));
return workInfo;
}
@Override
public WorkInfo getNullableResult(ResultSet resultSet, int i) throws SQLException {
System.out.println("getNullableResult int i ");
WorkInfo workInfo=this.StringToObject(resultSet.getString(i));
return workInfo;
}
@Override
public WorkInfo getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
System.out.println("getNullableResult CallableStatement ");
WorkInfo workInfo=this.StringToObject(callableStatement.getString(i));
return workInfo;
}
}
3.插入数据测试方法
@Test
public void testSave(){
for(long i=34;i<35;i++) {
User user = new User();
user.setId(400+i);
user.setAge((int)i+30);
user.setEmail("zoulinlin"+i+"@163.com");
user.setName("zouli"+i);
WorkInfo workInfo=new WorkInfo();
workInfo.setAdrees("suzhou");
workInfo.setCompany("build fuck");
workInfo.setTitle("ceo");
user.setWorkInfo(workInfo);
int row = userMapper.insert(user);
System.out.println(row);
}
}
运行log(可以看出在向数据库保存进行了转换):
2022-10-12 18:33:00.034 DEBUG 12076 --- [ main] c.m.service.mapper.UserMapper.insert : ==> Preparing: INSERT INTO user (specid, id, name, age, email, work_info, deleted, createtime, version, FAB) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'FAB1')
setNonNullParameter
String ObjectToString
3
2022-10-12 18:33:00.088 DEBUG 12076 --- [ main] c.m.service.mapper.UserMapper.insert : ==> Parameters: lot-20221012183257(String), 434(Long), zouli34(String), 64(Integer), zoulinlin34@163.com(String), title=ceo,Company=build fuck,adrees=suzhou(String), 0(Integer), 2022-10-12T18:32:57.180(LocalDateTime), 0(Long)
Consume Time:151 ms 2022-10-12 18:33:00
Execute SQL:INSERT INTO user (specid, id, name, age, email, work_info, deleted, createtime, version, FAB) VALUES ('lot-20221012183257', 434, 'zouli34', 64, 'zoulinlin34@163.com', 'title=ceo,Company=build fuck,adrees=suzhou', 0, '2022-10-12T18:32:57.180', 0, 'FAB1')
4.数据查询测试方法
@Test
public void testQuery(){
HashMap<String,Object> hashMap=new HashMap<String,Object>();
//hashMap.put("name","jack");
hashMap.put("id",434);
List<User> users= userMapper.selectByMap(hashMap);
users.forEach(System.out::println);
}
运行log(可以看出从数据库取数据时进行了转换):
2022-10-12 18:35:50.920 DEBUG 18236 --- [ main] c.m.s.mapper.UserMapper.selectByMap : ==> Preparing: SELECT specid, id, name, age, email, work_info, deleted, createtime, version, fab FROM user WHERE id = ? AND deleted = 0 AND user.FAB = 'FAB1'
2022-10-12 18:35:50.956 DEBUG 18236 --- [ main] c.m.s.mapper.UserMapper.selectByMap : ==> Parameters: 434(Integer)
Consume Time:13 ms 2022-10-12 18:35:50
Execute SQL:SELECT specid, id, name, age, email, work_info, deleted, createtime, version, fab FROM user WHERE id = 434 AND deleted = 0 AND user.FAB = 'FAB1'
getNullableResult String s
WorkInfo StringToObject
2022-10-12 18:35:50.994 DEBUG 18236 --- [ main] c.m.s.mapper.UserMapper.selectByMap : <== Total: 1
User(id=434, specid=lot-20221012183257, name=zouli34, age=64, email=zoulinlin34@163.com, workInfo=WorkInfo(title=ceo, Company=build fuck, adrees=suzhou), deleted=0, createtime=2022-10-12T18:32:57, version=0, fab=FAB1)
以上实例是告知怎么来实现,其实mybatis-plus提供了转jason格式的typehandler,如果想按照自已格式来进行需要按照以上方法来自行定义新类
public class FastjsonTypeHandler extends AbstractJsonTypeHandler<Object>
public class GsonTypeHandler extends AbstractJsonTypeHandler<Object>
public class JacksonTypeHandler extends AbstractJsonTypeHandler<Object>