使用mybatis作為操作數據庫的orm框架,操作基本數據類型時可以通過內置的類型處理器完成java數據類型和數據庫類型的轉換,但是對于擴展的數據類型要實現與數據庫類型的轉換就需要自定義類型轉換器完成,比如某個實體類型存儲到數據庫,可以轉換為json字符串存儲,讀取數據時再轉換為對應的實體類。
在mybatis中可以有兩種方式實現上面的方案:
一、直接繼承mybatis框架提供的 org.apache.ibatis.type.BaseTypeHandler
完成數據類型轉換;
二、如果項目引入了mybatis-plus,也可以繼承 com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler
實現數據類型轉換。
接下來分別介紹上面兩種方案的實現方式。
首先在數據庫中創建一個表用于測試數據存取:
CREATE TABLE `demo_data` (`id` int NOT NULL AUTO_INCREMENT,`detail` json NULL,`create_time` datetime NULL,PRIMARY KEY (`id`)
);
一、mybatis框架實現類型轉換
使用mybatis實現類型轉換,首先要自定義一個handler繼承自基礎的handler,再將自定義的handler注入到字段的typeHandler中就實現了類型轉換:
自定義handler:
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;/*** @Author xingo* @Date 2025/2/6*/
@MappedJdbcTypes({JdbcType.VARCHAR, JdbcType.CHAR})
public class DetailTypeHandler extends BaseTypeHandler<DemoData.DetailInfo> {@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, DemoData.DetailInfo parameter, JdbcType jdbcType) throws SQLException {ps.setString(i, JacksonUtils.toJSONString(parameter));}@Overridepublic DemoData.DetailInfo getNullableResult(ResultSet rs, String columnName) throws SQLException {return JacksonUtils.parseObject(rs.getString(columnName), DemoData.DetailInfo.class);}@Overridepublic DemoData.DetailInfo getNullableResult(ResultSet rs, int columnIndex) throws SQLException {return JacksonUtils.parseObject(rs.getString(columnIndex), DemoData.DetailInfo.class);}@Overridepublic DemoData.DetailInfo getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {return JacksonUtils.parseObject(cs.getString(columnIndex), DemoData.DetailInfo.class);}
}
上面就實現了java類型與數據庫類型的對應關系,就是將實體類中的java對象與數據庫中的字符串類型自動轉換:
import lombok.Data;import java.io.Serializable;
import java.time.LocalDateTime;/*** @Author xingo* @Date 2025/2/6*/
@Data
public class DemoData implements Serializable {private Integer id;private DemoData.DetailInfo detail;private LocalDateTime createTime;@Datapublic static class DetailInfo implements Serializable {private String name;private Integer age;private LocalDateTime dateTime;}
}
接下來就是在編寫的xml文件中將剛剛自定義的handler和實體類信息完成對應關系:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.xingo.demo.DemoDataMapper"><resultMap id="demoData" type="org.xingo.demo.DemoData"><id property="id" column="id"/><result property="detail" column="detail" typeHandler="org.xingo.demo.DetailTypeHandler"/><result property="createTime" column="create_time"/></resultMap><insert id="insertDemoData" useGeneratedKeys="true" keyProperty="id">insert into demo_data(detail, create_time)values (#{detail, typeHandler=org.xingo.demo.DetailTypeHandler}, #{createTime})</insert><update id="updateDemoData">update demo_dataset detail=#{detail, typeHandler=org.xingo.demo.DetailTypeHandler}create_time=#{createTime}where id=#{id}</update><select id="findDemoDataById" resultMap="demoData">select *from demo_datawhere id=#{id}</select>
</mapper>
xml對應的接口:
import org.xingo.demo.DemoData;/*** @Author xingo* @Date 2025/2/6*/
public interface DemoDataMapper {void insertDemoData(DemoData data);void updateDemoData(DemoData data);DemoData findDemoDataById(Integer id);
}
上面的幾步就實現了自定義數據類型與數據庫中字符串類型的轉換,測試上面接口可以完成數據的存取:
二、mybatis-plus框架實現類型轉換
使用mybatis實現自定義類型與數據庫類型的轉換相對來說還是有一點繁瑣,如果在項目中引入了mybatis-plus,那么就可以減少xml文件的編寫,直接在實體類的字段上添加注解完成xml文件的內容。
使用mybatis-plus實現類型轉換首先也是自定義handler類:
import com.baomidou.mybatisplus.extension.handlers.AbstractJsonTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;/*** @Author xingo* @Date 2025/2/6*/
@MappedTypes({DemoData.DetailInfo.class})
@MappedJdbcTypes({JdbcType.VARCHAR, JdbcType.CHAR})
public class DetailTypeHandler extends AbstractJsonTypeHandler<DemoData.DetailInfo> {@Overrideprotected DemoData.DetailInfo parse(String json) {return JacksonUtils.parseObject(json, DemoData.DetailInfo.class);}@Overrideprotected String toJson(DemoData.DetailInfo detail) {return JacksonUtils.toJSONString(detail);}
}
映射主要是通過實體類的注解完成的:
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;import java.io.Serializable;
import java.time.LocalDateTime;/*** @Author xingo* @Date 2025/2/6*/
@Data
@TableName(value = "demo_data", autoResultMap = true)
public class DemoData implements Serializable {@TableId(type = IdType.AUTO)private Integer id;@TableField(typeHandler = DetailTypeHandler.class)private DemoData.DetailInfo detail;@TableField(fill = FieldFill.INSERT)private LocalDateTime createTime;@Datapublic static class DetailInfo implements Serializable {private String name;private Integer age;private LocalDateTime dateTime;}
}
mapper接口只需要繼承mybatis-plus提供的基礎mapper就可以:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;/*** @Author xingo* @Date 2025/2/6*/
public interface DemoDataMapper extends BaseMapper<DemoData> {
}
通過上面的定義,所有基于mybatis-plus提供的增改查操作都可以完成字段類型轉換。
測試上面的內容在數據庫中產生的數據:
附:jackson工具類
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;/*** json工具** @Author xingo* @Date 2025/2/6*/
@Slf4j
public class JacksonUtils {private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();static {// Long類型處理,避免前端處理長整型時精度丟失SimpleModule module1 = new SimpleModule();module1.addSerializer(Long.class, ToStringSerializer.instance);module1.addSerializer(Long.TYPE, ToStringSerializer.instance);JavaTimeModule module2 = new JavaTimeModule();// java8日期處理module2.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));module2.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));module2.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));module2.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));module2.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));module2.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));OBJECT_MAPPER// 添加modules.registerModules(module1, module2, new Jdk8Module())// 日期類型不轉換為時間戳.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false).configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false)// 反序列化的時候如果多了其他屬性,不拋出異常.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)// 如果是空對象的時候,不拋異常.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)// 空對象不序列化.setSerializationInclusion(JsonInclude.Include.NON_NULL)// 日期格式化.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))// 設置時區.setTimeZone(TimeZone.getTimeZone("GMT+8"))// 駝峰轉下劃線// .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)// 語言.setLocale(Locale.SIMPLIFIED_CHINESE);}/*** 反序列化對象*/public static <T> T parseObject(String json, Class<T> clazz) {if (json == null) {return null;}try {return OBJECT_MAPPER.readValue(json, clazz);} catch (JsonProcessingException e) {e.printStackTrace();}return null;}/*** 反序列化對象*/public static JsonNode parseObject(String json) {if (json == null) {return null;}try {return OBJECT_MAPPER.readTree(json);} catch (JsonProcessingException e) {e.printStackTrace();}return null;}/*** 反序列化對象*/public static <T> T parseObject(String json, TypeReference<T> type) {if (json == null) {return null;}try {return OBJECT_MAPPER.readValue(json, type);} catch (JsonProcessingException e) {e.printStackTrace();}return null;}/*** 反序列化對象*/public static <T> T parseObject(byte[] bytes, TypeReference<T> type) {if (bytes == null) {return null;}try {return OBJECT_MAPPER.readValue(bytes, type);} catch (Exception e) {e.printStackTrace();}return null;}/*** 反序列化對象*/public static <T> T parseObject(JsonNode jsonNode, Class<T> clazz) {return jsonNode == null ? null : OBJECT_MAPPER.convertValue(jsonNode, clazz);}/*** 反序列化列表*/public static <T> List<T> parseArray(String json, Class<T> clazz) {if (json == null) {return null;}try {JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class, clazz);return OBJECT_MAPPER.treeToValue(OBJECT_MAPPER.readTree(json), javaType);} catch (Exception e) {e.printStackTrace();}return null;}/*** 反序列化列表*/public static <T> List<T> parseArray(JsonNode json, Class<T> clazz) {try {JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(List.class, clazz);return json == null ? null : OBJECT_MAPPER.treeToValue(json, javaType);} catch (JsonProcessingException e) {log.warn(e.getLocalizedMessage());return null;}}/*** 寫為json串*/public static String toJSONString(Object obj) {if (obj == null) {return null;}if (obj instanceof String) {return (String) obj;}try {return OBJECT_MAPPER.writeValueAsString(obj);} catch (JsonProcessingException e) {e.printStackTrace();}return null;}/*** 寫為字節數組*/public static byte[] toJSONBytes(Object obj) {if (obj == null) {return null;}try {return OBJECT_MAPPER.writeValueAsBytes(obj);} catch (Exception e) {e.printStackTrace();}return null;}/*** 獲取jackson對象*/public static ObjectMapper getObjectMapper() {return OBJECT_MAPPER;}/*** 美化輸出json格式*/public static String pretty(String json) throws IOException {return StringUtils.isBlank(json) ? json : pretty(JacksonUtils.getObjectMapper().readTree(json));}/*** 美化輸出json格式*/public static String pretty(JsonNode jsonNode) throws IOException {return null == jsonNode ? "" : JacksonUtils.getObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);}/*** 對象轉json*/public static JsonNode toJsonNode(Object obj) {if (obj instanceof String) {return parseObject((String) obj, JsonNode.class);}return obj == null ? null : OBJECT_MAPPER.convertValue(obj, JsonNode.class);}
}