Mybatis開(kāi)發(fā)要點(diǎn)-resultType和resultMap有什么區(qū)別詳解
Mybatis返回Xml返回值有resultType和resultMap,我們一般都該如何選擇呢?
一、resultType
1、resultType介紹
當(dāng)使用resultType做SQL語(yǔ)句返回結(jié)果類型處理時(shí),對(duì)于SQL語(yǔ)句查詢出的字段在相應(yīng)的pojo中必須有和它相同的字段對(duì)應(yīng),而resultType中的內(nèi)容就是pojo在本項(xiàng)目中的位置。
2、映射規(guī)則
- 基本類型 :resultType=基本類型
- List類型: resultType=List中元素的類型
- Map類型 單條記錄:resultType =map 多條記錄:resultType =Map中value的類型
3、自動(dòng)映射注意事項(xiàng)
- 前提:SQL列名和JavaBean的屬性是一致的;
- 使用resultType,如用簡(jiǎn)寫(xiě)需要配置typeAliases (別名);
- 如果列名和JavaBean不一致,但列名符合單詞下劃線分割,Java是駝峰命名法,則mapUnderscoreToCamelCase可設(shè)置為true;
4、代碼演示
1、t_user_test.sql準(zhǔn)備
CREATE TABLE `t_user_test` ( `id` int(20) NOT NULL AUTO_INCREMENT, `user_name` varchar(60) DEFAULT NULL COMMENT '用戶名稱', `real_name` varchar(60) DEFAULT NULL COMMENT '真實(shí)名稱', `sex` tinyint(3) DEFAULT NULL COMMENT '姓名', `mobile` varchar(20) DEFAULT NULL COMMENT '電話', `email` varchar(60) DEFAULT NULL COMMENT '郵箱', `note` varchar(200) DEFAULT NULL COMMENT '備注', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=142 DEFAULT CHARSET=utf8;碼
2、實(shí)體類
package com.enjoylearning.mybatis.entity; import java.io.Serializable; import java.util.List; import org.apache.ibatis.annotations.Param; import com.mysql.jdbc.Blob; public class TUser implements Serializable{ private Integer id; private String userName; private String realName; private Byte sex; private String mobile; private String email; private String note; private TPosition position; private List<TJobHistory> jobs ; private List<HealthReport> healthReports; private List<TRole> roles; @Override public String toString() { String positionId= (position == null ? "" : String.valueOf(position.getId())); return "TUser [id=" + id + ", userName=" + userName + ", realName=" + realName + ", sex=" + sex + ", mobile=" + mobile + ", email=" + email + ", note=" + note + ", positionId=" + positionId + "]"; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public Byte getSex() { return sex; } public void setSex(Byte sex) { this.sex = sex; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public TPosition getPosition() { return position; } public void setPosition(TPosition position) { this.position = position; } public List<TJobHistory> getJobs() { return jobs; } public void setJobs(List<TJobHistory> jobs) { this.jobs = jobs; } public List<HealthReport> getHealthReports() { return healthReports; } public void setHealthReports(List<HealthReport> healthReports) { this.healthReports = healthReports; } public List<TRole> getRoles() { return roles; } public void setRoles(List<TRole> roles) { this.roles = roles; } }
3、Mapper接口類
public interface TUserTestMapper { TUser selectByPrimaryKey(Integer id); List<TUser> selectAll(); }
4、Mapper 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.mybatis.mapper.TUserTestMapper"> <select id="selectByPrimaryKey" resultType="TUser"> select id, user_name, real_name, sex, mobile, email, note from t_user_test where id = #{id,jdbcType=INTEGER} </select> <select id="selectAll" resultType="TUser"> select id, user_name, real_name, sex, mobile, email, note from t_user_test </select> </mapper>
5、配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="db.properties"/> <settings> <!-- 設(shè)置自動(dòng)駝峰轉(zhuǎn)換 --> <setting name="mapUnderscoreToCamelCase" value="true" /> <!-- 開(kāi)啟懶加載 --> <!-- 當(dāng)啟用時(shí),有延遲加載屬性的對(duì)象在被調(diào)用時(shí)將會(huì)完全加載任意屬性。否則,每種屬性將會(huì)按需要加載。默認(rèn):true --> <setting name="aggressiveLazyLoading" value="false" /> </settings> <!-- 別名定義 --> <typeAliases> <package name="com.enjoylearning.mybatis.entity" /> </typeAliases> <plugins> <plugin interceptor="com.enjoylearning.mybatis.Interceptors.ThresholdInterceptor"> <property name="threshold" value="10"/> </plugin> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <property name="pageSizeZero" value="true" /> </plugin> </plugins> <!--配置environment環(huán)境 --> <environments default="development"> <!-- 環(huán)境配置1,每個(gè)SqlSessionFactory對(duì)應(yīng)一個(gè)環(huán)境 --> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://ip:port/test?useUnicode=true" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <!-- 映射文件,mapper的配置文件 --> <mappers> <!--直接映射到相應(yīng)的mapper文件 --> <mapper resource="sqlmapper/TUserTestMapper.xml" /> </mappers> </configuration>
6、啟動(dòng)測(cè)試類
public class MybatisDemo2 { private SqlSessionFactory sqlSessionFactory; @Before public void init() throws IOException { //--------------------第一階段--------------------------- // 1.讀取mybatis配置文件創(chuàng)SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // 1.讀取mybatis配置文件創(chuàng)SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); inputStream.close(); } @Test //知識(shí)點(diǎn):resultType public void testAutoMapping() throws IOException { // 2.獲取sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 3.獲取對(duì)應(yīng)mapper TUserTestMapper mapper = sqlSession.getMapper(TUserTestMapper.class); // 4.執(zhí)行查詢語(yǔ)句并返回多條數(shù)據(jù) List<TUser> users = mapper.selectAll(); for (TUser tUser : users) { System.out.println(tUser); } } }
7、執(zhí)行結(jié)果
sql語(yǔ)句:“com.mysql.jdbc.JDBC4PreparedStatement@654f0d9c: select id, user_name, real_name, sex, mobile, email, note from t_user_test”執(zhí)行時(shí)間為:35毫秒,已經(jīng)超過(guò)閾值! TUser [id=1, userName=zhangsan, realName=張三, sex=1, mobile=186995587411, email=zhangsan@qq.com, note=zhangsan的備注, positionId=] TUser [id=2, userName=lisi, realName=李四, sex=1, mobile=18677885200, email=lisi@qq.com, note=lisi的備注, positionId=] TUser [id=3, userName=wangwu, realName=王五, sex=2, mobile=18695988747, email=xxoo@163.com, note=wangwu's note, positionId=]
resultType當(dāng)返基本類型的時(shí)候建議選擇,當(dāng)返回POJO類的時(shí)候由于需要完全和數(shù)據(jù)庫(kù)字段進(jìn)行對(duì)應(yīng),存在不靈活、問(wèn)題排查難等問(wèn)題。
二、resultMap
1、resultMap 介紹
resultMap 元素是 MyBatis 中最重要最強(qiáng)大的元素。它可以讓你從 90% 的 JDBC ResultSets 數(shù)據(jù)提取代碼中解放出來(lái),在對(duì)復(fù)雜語(yǔ)句進(jìn)行聯(lián)合映射的時(shí)候,它很可能可以代替數(shù)千行的同等功能的代碼。ResultMap 的設(shè)計(jì)思想是,簡(jiǎn)單的語(yǔ)句不需要明確的結(jié)果映射,而復(fù)雜一點(diǎn)的語(yǔ)句只需要描述它們的關(guān)系就行了。
2、resultMap屬性
屬性 | 描述 |
id | 當(dāng)前命名空間中的一個(gè)唯一標(biāo)識(shí),用于標(biāo)識(shí)一個(gè)result map. |
type | 類的完全限定名, 或者一個(gè)類型別名. |
autoMapping | 如果設(shè)置這個(gè)屬性,MyBatis將會(huì)為這個(gè)ResultMap開(kāi)啟或者關(guān)閉自動(dòng)映射。這個(gè)屬性會(huì)覆蓋全局的屬性 autoMappingBehavior。默認(rèn)值為:unset。 |
3、使用場(chǎng)景
- 字段有自定義的轉(zhuǎn)化規(guī)則
- 復(fù)雜的多表查詢
4、resultMap子元素屬性
- id –一個(gè) ID 結(jié)果;標(biāo)記出作為 ID 的結(jié)果可以幫助提高整體性能,一對(duì)多的查詢中用于結(jié)果集合并;
- result – 注入到字段或 JavaBean 屬性的普通結(jié)果
- association – 一個(gè)復(fù)雜類型的關(guān)聯(lián);許多結(jié)果將包裝成這種類型。關(guān)聯(lián)可以指定為一個(gè) resultMap 元素,或者引用一個(gè)
- collection – 一個(gè)復(fù)雜類型的集合
5、代碼演示
實(shí)體類,配置文件同上
1、mapper接口
public interface TUserMapper { List<TUser> selectTestResultMap(); }
2、Mapper.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.mybatis.mapper.TUserMapper"> <resultMap id="UserResultMap" type="TUser" autoMapping="true"> <id column="id" property="id" /> <result column="userName" property="userName"/> <result column="realName" property="realName" /> <result column="sex" property="sex" /> <result column="mobile" property="mobile" /> <result column="email" property="email" /> <result column="note" property="note" /> <association property="position" javaType="TPosition" columnPrefix="post_"> <id column="id" property="id"/> <result column="name" property="postName"/> <result column="note" property="note"/> </association> </resultMap> <select id="selectTestResultMap" resultMap="UserResultMap" > select a.id, userName, realName, sex, mobile, email, a.note, b.id post_id, b.post_name, b.note post_note from t_user a, t_position b where a.position_id = b.id </select> </mapper>
3、啟動(dòng)測(cè)試
public class MybatisDemo2 { private SqlSessionFactory sqlSessionFactory; @Before public void init() throws IOException { //--------------------第一階段--------------------------- // 1.讀取mybatis配置文件創(chuàng)SqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // 1.讀取mybatis配置文件創(chuàng)SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); inputStream.close(); } @Test public void testResultMap() throws IOException { //--------------------第二階段--------------------------- // 2.獲取sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 3.獲取對(duì)應(yīng)mapper TUserMapper mapper = sqlSession.getMapper(TUserMapper.class); //--------------------第三階段--------------------------- // 4.執(zhí)行查詢語(yǔ)句并返回單條數(shù)據(jù) List<TUser> users = mapper.selectTestResultMap(); for (TUser tUser : users) { System.out.println(tUser.getUserName()); System.out.println(tUser.getPosition().getPostName()); } } }
4、執(zhí)行結(jié)果
sql語(yǔ)句:“com.mysql.jdbc.JDBC4PreparedStatement@19bb07ed: select
a.id,
userName,
realName,
sex,
mobile,
email,
a.note,
b.id post_id,
b.post_name,
b.note post_note
from t_user a,
t_position b
where a.position_id = b.id”執(zhí)行時(shí)間為:52毫秒,已經(jīng)超過(guò)閾值!
zhangsan
總經(jīng)理
lisi
零時(shí)工
wangwu
總經(jīng)理
三、結(jié)論
當(dāng)返回對(duì)象為基礎(chǔ)類型時(shí)建議走resultType,當(dāng)返回對(duì)象為POJO時(shí),強(qiáng)制走resultMap。同時(shí)可以參考阿里巴巴JAVA開(kāi)發(fā)手冊(cè)中的5.4.3節(jié),返回要解耦,不訥訥更直接使用resultClass。
到此這篇關(guān)于Mybatis開(kāi)發(fā)要點(diǎn)-resultType和resultMap有什么區(qū)別詳解的文章就介紹到這了,更多相關(guān)Mybatis -resultType resultMap內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 三分鐘讀懂mybatis中resultMap和resultType區(qū)別
- Java?MyBatis傳出參數(shù)resultType和resultMap解讀
- MyBatis中resultType和parameterType和resultMap使用總結(jié)
- MyBatis標(biāo)簽之Select?resultType和resultMap詳解
- 詳解MyBatis resultType與resultMap中的幾種返回類型
- MyBatis中resultMap和resultType的區(qū)別詳解
- MyBatis中關(guān)于resultType和resultMap的區(qū)別介紹
- 深入理解Mybatis中的resultType和resultMap
- Mybatis中的resultType和resultMap查詢操作實(shí)例詳解
- Mybatis返回值(resultType&resultMap)的具體使用
相關(guān)文章
SpringBoot攔截器實(shí)現(xiàn)登錄攔截的示例代碼
本文主要介紹了SpringBoot攔截器實(shí)現(xiàn)登錄攔截,文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03最新log4j2遠(yuǎn)程代碼執(zhí)行漏洞(附解決方法)
Apache?Log4j2?遠(yuǎn)程代碼執(zhí)行漏洞攻擊代碼,該漏洞利用無(wú)需特殊配置,經(jīng)多方驗(yàn)證,Apache?Struts2、Apache?Solr、Apache?Druid、Apache?Flink等均受影響,本文就介紹一下解決方法2021-12-12IDEA+JRebel實(shí)現(xiàn)全自動(dòng)熱部署的方法步驟
這篇文章主要介紹了IDEA+JRebel實(shí)現(xiàn)全自動(dòng)熱部署的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11IDEA創(chuàng)建Servlet并配置web.xml的實(shí)現(xiàn)
這篇文章主要介紹了IDEA創(chuàng)建Servlet并配置web.xml的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10