Mybatis之映射實體類中不區(qū)分大小寫的解決
Mybatis 映射實體類中不區(qū)分大小寫
做項目時候遇到一個Bug,實體類中有兩個字段,例如(addTime,addtime),進(jìn)行查詢搜索會發(fā)生神奇的事情
<?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="cn.runlin.jetta.mapper.JettaUpgradeLogMapper"> <resultMap id="BaseResultMap" type="cn.runlin.jetta.entity.JettaUpgradeLog"> <id column="upgrade_id" jdbcType="INTEGER" property="upgradeId" /> <result column="task_id" jdbcType="INTEGER" property="taskId" /> <result column="task_name" jdbcType="VARCHAR" property="taskName" /> <result column="task_version" jdbcType="VARCHAR" property="taskVersion" /> <result column="project_id" jdbcType="INTEGER" property="projectId" /> <result column="project_name" jdbcType="VARCHAR" property="projectName" /> <result column="project_type" jdbcType="TINYINT" property="projectType" /> <result column="dealer_id" jdbcType="INTEGER" property="dealerId" /> <result column="dealer_name" jdbcType="VARCHAR" property="dealerName" /> <result column="service_code" jdbcType="VARCHAR" property="serviceCode" /> <result column="add_time" jdbcType="TIMESTAMP" property="addTime" /> <result column="addtime" jdbcType="INTEGER" property="addtime" /> <result column="status" jdbcType="INTEGER" property="status" /> <result column="reasonname" jdbcType="VARCHAR" property="reasonname" /> </resultMap> <sql id="Base_Column_List"> upgrade_id, task_id, task_name, task_version, project_id, project_name, project_type, dealer_id, dealer_name, service_code, add_time, addtime </sql> //映射到實體類 而不使用xml文件中的BaseResultMap <select id="getJettaUpgradeLogList" resultType="cn.runlin.jetta.entity.JettaUpgradeLog" parameterType="Map"> select jul.upgrade_id, task_id, task_name, task_version, project_id, project_name, project_type, dealer_id, dealer_name, service_code, add_time, status, reasonname from jetta_upgrade_log jul LEFT OUTER JOIN jetta_upgrade_log_status juls ON jul.upgrade_id=juls.upgrade_id LEFT OUTER JOIN jetta_status_code jsc ON juls.status_id= jsc.rid <where> <if test="serviceCode != null and serviceCode !='' "> AND jul.service_code like concat("%",#{serviceCode},"%") </if> <if test="dealerName != null and dealerName !='' "> AND jul.dealer_name like concat("%",#{dealerName},"%") </if> <if test="taskVersion != null and taskVersion !='' "> AND jul.task_version like concat("%",#{taskVersion},"%") </if> <if test="status != null and status !='' "> AND juls.status like concat("%",#{status},"%") </if> </where> </select> </mapper>
會報addTime是時間戳類型,不能轉(zhuǎn)換成INTEGER類型的問題。原因就是mybatis映射實體類之后,不能區(qū)分大小寫,而造成字段類型對應(yīng)錯誤的問題
解決辦法
把映射實體類變成映射到xml中所設(shè)置的resultMap,就可以解決這個問題
<?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="cn.runlin.jetta.mapper.JettaUpgradeLogMapper"> <resultMap id="BaseResultMap" type="cn.runlin.jetta.entity.JettaUpgradeLog"> <id column="upgrade_id" jdbcType="INTEGER" property="upgradeId" /> <result column="task_id" jdbcType="INTEGER" property="taskId" /> <result column="task_name" jdbcType="VARCHAR" property="taskName" /> <result column="task_version" jdbcType="VARCHAR" property="taskVersion" /> <result column="project_id" jdbcType="INTEGER" property="projectId" /> <result column="project_name" jdbcType="VARCHAR" property="projectName" /> <result column="project_type" jdbcType="TINYINT" property="projectType" /> <result column="dealer_id" jdbcType="INTEGER" property="dealerId" /> <result column="dealer_name" jdbcType="VARCHAR" property="dealerName" /> <result column="service_code" jdbcType="VARCHAR" property="serviceCode" /> <result column="add_time" jdbcType="TIMESTAMP" property="addTime" /> <result column="addtime" jdbcType="INTEGER" property="addtime" /> <result column="status" jdbcType="INTEGER" property="status" /> <result column="reasonname" jdbcType="VARCHAR" property="reasonname" /> </resultMap> <sql id="Base_Column_List"> upgrade_id, task_id, task_name, task_version, project_id, project_name, project_type, dealer_id, dealer_name, service_code, add_time, addtime </sql> //映射到xml的BaseResultMap <select id="getJettaUpgradeLogList" resultMap="BaseResultMap" parameterType="Map"> select jul.upgrade_id, task_id, task_name, task_version, project_id, project_name, project_type, dealer_id, dealer_name, service_code, add_time, status, reasonname from jetta_upgrade_log jul LEFT OUTER JOIN jetta_upgrade_log_status juls ON jul.upgrade_id=juls.upgrade_id LEFT OUTER JOIN jetta_status_code jsc ON juls.status_id= jsc.rid <where> <if test="serviceCode != null and serviceCode !='' "> AND jul.service_code like concat("%",#{serviceCode},"%") </if> <if test="dealerName != null and dealerName !='' "> AND jul.dealer_name like concat("%",#{dealerName},"%") </if> <if test="taskVersion != null and taskVersion !='' "> AND jul.task_version like concat("%",#{taskVersion},"%") </if> <if test="status != null and status !='' "> AND juls.status like concat("%",#{status},"%") </if> </where> </select> </mapper>
問題解決
Mybatis的一些小細(xì)節(jié)
Mybatis要解決的問題:
1. 將sql語句硬編碼到j(luò)ava代碼中,如果修改sql語句,需要修改java代碼,重新編譯。系統(tǒng)可維護(hù)性不高。
設(shè)想如何解決?
能否將sql單獨配置在配置文件中。
2. 數(shù)據(jù)庫連接頻繁開啟和釋放,對數(shù)據(jù)庫的資源是一種浪費。
設(shè)想如何解決?
使用數(shù)據(jù)庫連接池管理數(shù)據(jù)庫連接。
3. 向preparedStatement中占位符的位置設(shè)置參數(shù)時,存在硬編碼(占位符的位置,設(shè)置的變量值)
設(shè)想如何解決?
能否也通過配置的方式,配置設(shè)置的參數(shù),自動進(jìn)行設(shè)置參數(shù)
4. 解析結(jié)果集時存在硬編碼(表的字段名、字段的類型)
設(shè)想如何解決?
能否將查詢結(jié)果集映射成java對象。
問題一. #{}和${}的區(qū)別是什么?
#{}是預(yù)編譯處理,${}是字符串替換。
Mybatis在處理#{}時,會將sql中的#{}替換為?號,調(diào)用PreparedStatement的set方法來賦值;
Mybatis在處理時,就是把{}替換成變量的值。
使用#{}可以有效的防止SQL注入,提高系統(tǒng)安全性。
問題二. 當(dāng)實體類中的屬性名和表中的字段名不一樣,怎么辦
第1種: 通過在查詢的sql語句中定義字段名的別名,讓字段名的別名和實體類的屬性名一致
<select id=”selectorder” parametertype=”int” resultetype=”me.gacl.domain.order”> select order_id id, order_no orderno ,order_price price form orders where order_id=#{id}; </select>
第2種: 通過<resultMap>來映射字段名和實體類屬性名的一一對應(yīng)的關(guān)系
<select id="getOrder" parameterType="int" resultMap="orderresultmap"> select * from orders where order_id=#{id} </select> <resultMap type=”me.gacl.domain.order” id=”orderresultmap”> <!–用id屬性來映射主鍵字段–> <id property=”id” column=”order_id”> <!–用result屬性來映射非主鍵字段,property為實體類屬性名,column為數(shù)據(jù)表中的屬性–> <result property = “orderno” column =”order_no”/> <result property=”price” column=”order_price” /> </reslutMap>
問題三. 模糊查詢like語句該怎么寫
string wildcardname = “smi”; list<name> names = mapper.selectlike(wildcardname); <select id=”selectlike”> select * from foo where bar like "%"#{value}"%" </select>
1.表達(dá)式: name like"%"#{name}"%" #起到占位符的作用
2.表達(dá)式: name like '%${name}%' $進(jìn)行字符串的拼接,直接把傳入的值,拼接上去了,沒有任何問題
表達(dá)式: name likeconcat(concat('%',#{username}),'%') 這是使用了cancat進(jìn)行字符串的連接,同時使用了#進(jìn)行占位
表達(dá)式:name like CONCAT('%','${name}','%') 對上面的表達(dá)式進(jìn)行了簡化,更方便了
問題四. 通常一個Xml映射文件
都會寫一個Dao接口與之對應(yīng),請問,這個Dao接口的工作原理是什么?Dao接口里的方法,參數(shù)不同時,方法能重載嗎?
Dao接口,就是人們常說的Mapper接口,接口的全限名,就是映射文件中的namespace的值,接口的方法名,就是映射文件中MappedStatement的id值,接口方法內(nèi)的參數(shù),就是傳遞給sql的參數(shù)。
Mapper接口是沒有實現(xiàn)類的,當(dāng)調(diào)用接口方法時,接口全限名+方法名拼接字符串作為key值,可唯一定位一個MappedStatement,舉例:com.mybatis3.mappers.StudentDao.findStudentById,可以唯一找到namespace為com.mybatis3.mappers.StudentDao下面id = findStudentById的MappedStatement。在Mybatis中,每一個<select>、<insert>、<update>、<delete>標(biāo)簽,都會被解析為一個MappedStatement對象。
Dao接口里的方法,是不能重載的,因為是全限名+方法名的保存和尋找策略。
Dao接口的工作原理是JDK動態(tài)代理,Mybatis運行時會使用JDK動態(tài)代理為Dao接口生成代理proxy對象(如使用spring會注入到容器中),代理對象proxy會攔截接口方法,轉(zhuǎn)而執(zhí)行MappedStatement所代表的sql,然后將sql執(zhí)行結(jié)果返回。
問題五. Mybatis是如何將sql執(zhí)行結(jié)果封裝為目標(biāo)對象并返回的
都有哪些映射形式?
答:第一種是使用<resultMap>標(biāo)簽,逐一定義列名和對象屬性名之間的映射關(guān)系。
第二種是使用sql列的別名功能,將列別名書寫為對象屬性名,比如T_NAME AS NAME,對象屬性名一般是name,小寫,但是列名不區(qū)分大小寫,Mybatis會忽略列名大小寫,智能找到與之對應(yīng)對象屬性名,你甚至可以寫成T_NAME AS NaMe,Mybatis一樣可以正常工作。
有了列名與屬性名的映射關(guān)系后,Mybatis通過反射創(chuàng)建對象,同時使用反射給對象的屬性逐一賦值并返回,那些找不到映射關(guān)系的屬性,是無法完成賦值的。
問題六. 如何獲取自動生成的(主)鍵值
insert 方法總是返回一個int值 - 這個值代表的是插入的行數(shù)。
而自動生成的鍵值在 insert 方法執(zhí)行完后可以被設(shè)置到傳入的參數(shù)對象中。
示例:
<insert id="insertUserMessage" parameterType="com.xxx.xxx.model.UserMessage" useGeneratedKeys="true" keyProperty="userMessage.id"> insert into my_news (orderid,commentid,type,title,content,createtime) values (#{userMessage.orderid},#{userMessage.commentid},#{userMessage.type},#{userMessage.title} ,#{userMessage.content},#{userMessage.createtime}) </insert>
這里需要注意的是需要把實體類傳進(jìn)來。keyProperty為自增的id字段。調(diào)用insert后自動將自增id賦值進(jìn)insert調(diào)用的實體類中
//新建對象 UserMessage userMessage = new UserMessage(); userMessage.setXxxxxx(xxxxxx); userMessageDao.insertUserMessage(userMessage); //這時userMessage.getId()就可以獲取到自增主鍵了 BigInteger id = userMessage.getId();
問題七. 在mapper中如何傳遞多個參數(shù)
第1種:
//DAO層的函數(shù) Public UserselectUser(String name,String area); //對應(yīng)的xml,#{0}代表接收的是dao層中的第一個參數(shù),#{1}代表dao層中第二參數(shù),更多參數(shù)一致往后加即可。 <select id="selectUser"resultMap="BaseResultMap"> select * fromuser_user_t whereuser_name = #{0} anduser_area=#{1} </select>
第2種: 使用 @param 注解:
import org.apache.ibatis.annotations.param; public interface usermapper { user selectuser(@param(“username”) string username, @param(“hashedpassword”) string hashedpassword); }
然后,就可以在xml像下面這樣使用(推薦封裝為一個map,作為單個參數(shù)傳遞給mapper
<select id=”selectuser” resulttype=”user”> select id, username, hashedpassword from some_table where username = #{username} and hashedpassword = #{hashedpassword} </select>
問題八. Mybatis動態(tài)sql是做什么的
都有哪些動態(tài)sql?能簡述一下動態(tài)sql的執(zhí)行原理不?
Mybatis動態(tài)sql可以讓我們在Xml映射文件內(nèi),以標(biāo)簽的形式編寫動態(tài)sql,完成邏輯判斷和動態(tài)拼接sql的功能。
Mybatis提供了9種動態(tài)sql標(biāo)簽:trim|where|set|foreach|if|choose|when|otherwise|bind。
其執(zhí)行原理為,從sql參數(shù)對象中計算表達(dá)式的值,根據(jù)表達(dá)式的值動態(tài)拼接sql,以此來完成動態(tài)sql的功能。
比如:
<select id="findUserById" resultType="user"> select * from user where <if test="id != null"> id=#{id} </if> and deleteFlag=0; </select>
問題九. Mybatis的Xml映射文件中
不同的Xml映射文件,id是否可以重復(fù)?
不同的Xml映射文件,如果配置了namespace,那么id可以重復(fù);如果沒有配置namespace,那么id不能重復(fù);畢竟namespace不是必須的,只是最佳實踐而已。
原因就是namespace+id是作為Map<String, MappedStatement>的key使用的,如果沒有namespace,就剩下id,那么,id重復(fù)會導(dǎo)致數(shù)據(jù)互相覆蓋。有了namespace,自然id就可以重復(fù),namespace不同,namespace+id自然也就不同。
問題十. 為什么說Mybatis是半自動ORM映射工具
它與全自動的區(qū)別在哪里?
Hibernate屬于全自動ORM映射工具,使用Hibernate查詢關(guān)聯(lián)對象或者關(guān)聯(lián)集合對象時,可以根據(jù)對象關(guān)系模型直接獲取,所以它是全自動的。而Mybatis在查詢關(guān)聯(lián)對象或關(guān)聯(lián)集合對象時,需要手動編寫sql來完成,所以,稱之為半自動ORM映射工具。
問題十一. 一對一、一對多的關(guān)聯(lián)查詢
<mapper namespace="com.lcb.mapping.userMapper"> <!--association 一對一關(guān)聯(lián)查詢 --> <select id="getClass" parameterType="int" resultMap="ClassesResultMap"> select * from class c,teacher t where c.teacher_id=t.t_id and c.c_id=#{id} </select> <resultMap type="com.lcb.user.Classes" id="ClassesResultMap"> <!-- 實體類的字段名和數(shù)據(jù)表的字段名映射 --> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="com.lcb.user.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> </resultMap> <!--collection 一對多關(guān)聯(lián)查詢 --> <select id="getClass2" parameterType="int" resultMap="ClassesResultMap2"> select * from class c,teacher t,student s where c.teacher_id=t.t_id and c.c_id=s.class_id and c.c_id=#{id} </select> <resultMap type="com.lcb.user.Classes" id="ClassesResultMap2"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="com.lcb.user.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <collection property="student" ofType="com.lcb.user.Student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultMap> </mapper>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
在?Spring?Boot?中使用?Quartz?調(diào)度作業(yè)的示例詳解
這篇文章主要介紹了在?Spring?Boot?中使用?Quartz?調(diào)度作業(yè)的示例詳解,在本文中,我們將看看如何使用Quartz框架來調(diào)度任務(wù),Quartz支持在特定時間運行作業(yè)、重復(fù)作業(yè)執(zhí)行、將作業(yè)存儲在數(shù)據(jù)庫中以及Spring集成,需要的朋友可以參考下2022-07-07SpringBoot中整合MyBatis-Plus-Join使用聯(lián)表查詢的實現(xiàn)
本文主要介紹了SpringBoot中整合MyBatis-Plus-Join使用聯(lián)表查詢的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03java中BCryptPasswordEncoder密碼的加密與驗證方式
這篇文章主要介紹了java中BCryptPasswordEncoder密碼的加密與驗證方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08Java?LinkedList實現(xiàn)班級信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Java?LinkedList實現(xiàn)班級信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02Java避免UTF-8的csv文件打開中文出現(xiàn)亂碼的方法
這篇文章主要介紹了Java避免UTF-8的csv文件打開中文出現(xiàn)亂碼的方法,結(jié)合實例形式分析了java操作csv文件時使用utf-16le編碼與utf8編碼相關(guān)操作技巧,需要的朋友可以參考下2019-07-07