這篇文章給大家分享的是有關(guān)Mybatis如何自定義TypeHandler解決特殊類型轉(zhuǎn)換問題的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

創(chuàng)新互聯(lián)公司是一家專業(yè)提供平陽企業(yè)網(wǎng)站建設(shè),專注與網(wǎng)站建設(shè)、成都做網(wǎng)站、H5網(wǎng)站設(shè)計、小程序制作等業(yè)務(wù)。10年已為平陽眾多企業(yè)、政府機構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)絡(luò)公司優(yōu)惠進(jìn)行中。
我們知道,Java和MySQL中的數(shù)據(jù)類型是不同的,Java中除了基本數(shù)據(jù)類型,還有對象。
有時候使用MySQL存儲數(shù)據(jù),或者從MySQL中讀取數(shù)據(jù)時,會有一些特殊需求 weary ,比如:
將Integer數(shù)組直接存入MySQL,保存為BLOB形式,讀取出來時又是正常的Integer數(shù)組 將Integer數(shù)組轉(zhuǎn)換為String,然后存入MySQL,使用varchar類型,讀取出來時又是正常的Integer數(shù)組
這也太難了叭!
解決辦法有兩種:
Basic Method:Java在存入數(shù)據(jù)之前,或讀取數(shù)據(jù)之后,做手動類型轉(zhuǎn)換 Clever Method:定義TypeHandler,并在Mybatis對應(yīng)位置指明
關(guān)于第一種方法這里不予贅述,不夠Smart。這里主要講述如何自定義Handler,來解決Java數(shù)據(jù)->MySQL數(shù)據(jù)的特殊類型轉(zhuǎn)換問題grinning
這種Handler不僅方便了我們的數(shù)據(jù)庫操作,還有利于代碼的復(fù)用。
這里以Integer[]數(shù)組的存儲為形如,1,2,3,的varchar字符串為例。
問題示例
我們定義一個role類,與數(shù)據(jù)庫的role表對應(yīng):
public class Role { private Integer id; private String name; private Integer[] accessIds; private Date createTime; // ... ignore get and set methods}
注意到里面有一個accessIds字段,它的類型是Integer[]
數(shù)據(jù)庫設(shè)計:
DROP TABLE IF EXISTS `role`;CREATE TABLE `role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `access_ids` varchar(255) DEFAULT NULL, `create_time` datetime NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;-- ------------------------------ Records of role-- ----------------------------INSERT INTO `role` VALUES ('1', '測試角色', ',1,2,', '2019-11-14 13:43:14');
自定義Handler類
通過繼承BaseTypeHandler類,重寫其方法,定義一個Integer[]與數(shù)據(jù)庫varchar類型自動轉(zhuǎn)換的Handler類:
/** * Java Int數(shù)組與MySQL String轉(zhuǎn)換器 * 比如[1,2,3] --> ",1,2,3," */public class StringToIntArrayHandler extends BaseTypeHandler<Integer[]> { private static final String splitCharset = ","; @Override public void setNonNullParameter(PreparedStatement ps, int i, Integer[] objects, JdbcType jdbcType) throws SQLException { String str = arrayToString(objects); ps.setString(i, str); } @Override public Integer[] getNullableResult(ResultSet rs, String columnName) throws SQLException { String str = rs.getString(columnName); return stringToArray(str); } @Override public Integer[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException { String str = rs.getString(columnIndex); return stringToArray(str); } @Override public Integer[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String str = cs.getString(columnIndex); return stringToArray(str); } // --- private methods --- /** * Integer數(shù)組轉(zhuǎn)String * 注:使用提前設(shè)定好的分隔符分割數(shù)組的每一項 */ private static String arrayToString(Integer[] array) { StringBuilder res = new StringBuilder(); if (array != null && array.length > 0) { for (Object o : array) { res.append(splitCharset).append(o.toString()); } res.append(splitCharset); } return res.length() > 0 ? res.toString() : null; } /** * 從String轉(zhuǎn)Integer數(shù)組 * 注:String是用分隔符分割的,使用String.split方法可以分解為數(shù)組 */ private static Integer[] stringToArray(String str) { List<Integer> list = new ArrayList<>(); if (str != null) { String[] array = str.split(splitCharset); if (array.length > 0) { for (String o : array) { if (o != null && o.length() > 0) { list.add(Integer.parseInt(o)); } } } } return list.toArray(new Integer[0]); }}
這個類的具體作用是什么呢?
當(dāng)Java中類型是Integer[]時,使用這個Handler類,將Integer[]轉(zhuǎn)換為以,號分割的字符串,然后存入數(shù)據(jù)庫 當(dāng)從數(shù)據(jù)庫讀取以,分割值的字符串時,可以通過這個Handler,自動將字符串轉(zhuǎn)換為Integer[]數(shù)組
下面我們演示一下具體的使用smile
在Mybatis中應(yīng)用自定義的Handler
Mybatis存放SQL語句的XML文件:
<?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="com.example.model.dao.RoleDAO"> <resultMap id="roleMap" type="com.example.model.bean.Role"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="accessIds" column="access_ids" typeHandler="ccom.example.model.dao.handler.StringToIntArrayHandler"/> <result property="createTime" column="create_time"/> </resultMap> <select id="findById" parameterType="map" resultMap="roleMap"> SELECT id, name, access_ids, create_time FROM role WHERE id = #{id} </select> <insert id="insert" parameterType="com.example.model.bean.Role"> <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO role (name, create_time, access_ids) VALUES (#{name}, #{createTime} , #{accessIds, jdbcType=VARCHAR, typeHandler=com.example.model.dao.handler.StringToIntArrayHandler}) </insert></mapper>
感謝各位的閱讀!關(guān)于“Mybatis如何自定義TypeHandler解決特殊類型轉(zhuǎn)換問題”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
網(wǎng)站名稱:Mybatis如何自定義TypeHandler解決特殊類型轉(zhuǎn)換問題
分享路徑:http://www.chinadenli.net/article12/iphigc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、移動網(wǎng)站建設(shè)、企業(yè)網(wǎng)站制作、網(wǎng)站內(nèi)鏈、小程序開發(fā)、商城網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)