歡迎查看Java開發之上帝之眼系列教程,如果您正在為Java后端龐大的體系所困擾,如果您正在為各種繁出不窮的技術和各種框架所迷茫,那么本系列文章將帶您窺探Java龐大的體系。本系列教程希望您能站在上帝的角度去觀察(了解)Java體系。使Java的各種后端技術在你心中模塊化;讓你在工作中能將Java各個技術了然於心;能夠即插即用。本章我們來一起了解ORM(對象關系映射關系)框架之Mybatis(Ibatis)。
主流ORM框架有Mybatis和Hibernate,本章我們將對Mybatis的核心要點進行了解。
什么是ORM(對象映射關系)框架?
ORM(Object Relational Mapping)對象關系映射,是 一種為了解決面向對象與關系型數據庫不匹配而出現的技術,使開發者能夠用面向對象的方式使用關系型數據庫。
Mybatis和Hibernate有什么異同?
- Mybatis簡單,Hibernate較復雜,門檻高。
- Mybatis自定制Sql,比Hibernate靈活,可控
- Mybatis與數據庫映射得到的PO與Hibernate映射PO意義不同
Mybatis入門起步 Mybatis入門起步完整示例下載
/** * @Author:jimisun * @Description: * @Date:Created in 08:37 2018-09-24 * @Modified By: */ public class Main { public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); TestUserMapper mapper = sqlSession.getMapper(TestUserMapper.class); TestUser testUser = mapper.selectOne(1); System.out.println(testUser.toString()); } }
PS:Mybatis支持注解開發,但需要保留空的XML文件,也就是保留空的命名空間 ; 如下所示
@Select(" SELECT * from user where id = #{id};")
MyDto selectOne(Integer id);
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.jimisun.dao.TestUserMapper"> <!--空--> </mapper>
Mybatis和Spring的集成 Myabtis和Spring整合完整示例代碼下載
如果你使用Mybatis那么一定會使用Spring,最常見的框架組合就是SSM(SpringMvc+Spring+Mybatis),那么Mybatis針對和Spring的整合提供了一個類庫(jar包)
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency>
以前我們配置在mybatis里面的配置,現在我們可以將這些配置轉移到了Spring配置中;統一交給Spring進行管理, Mybatis的配置文件留空,但是不能刪除喲
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 加載配置文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 數據庫連接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="maxActive" value="10"/> </bean> <!-- mapper配置 --> <!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 數據庫連接池 --> <property name="dataSource" ref="dataSource"/> <!-- 加載mybatis的全局配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 掃描entity包 使用別名 --> <property name="typeAliasesPackage" value="com.jimisun.domain"/> <!-- 掃描sql配置文件:mapper需要的xml文件 --> <property name="mapperLocations" value="classpath:mapper/*.xml" /> </bean> <!-- 配置掃描Dao接口包,動態實現Dao接口,注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- 給出需要掃描Dao接口包 --> <property name="basePackage" value="com.jimisun.dao"/> </bean> </beans>
Spring和Myabtis整合的有兩個關注點
- Myabtis將SqlSessionFactory交付Spring管理
- Spring將XML對應的接口進行接手管理
Mybatis結果映射 Myabtis自定義結果映射完整示例代碼下載
在實際項目中我們通過使用mybatis查詢數據庫經常使用多表查詢,關聯查詢,或者實體的屬性名和數據庫列名不符等情況...所以查詢的結果存在不定性,我們可以自定義Dto類,在mapper.xml文件中自定義
<resultMap>標簽即可。
<resultMap id="MyDto" type="com.jimisun.domain.dto.MyDto"> <result property="myid" column="id"></result> <result property="myusername" column="username"></result> </resultMap>
Mybatis二級緩存 Mybatis的二級緩存測試示例代碼
雖然很多時候我們在開發中並不經常Mybatis的二級緩存 , 但是如果針對個別SQL進行優化設置能夠極大提升訪問數據庫效率 . mybatis支持一級緩存和二級緩存,默認開啟一級緩存,一級緩存使SqlSession級別的,Session結束緩存就清空了,二級緩存使Mapper級別的,需要我們手動開啟。
<!--開啟二級緩存--> <cache/>
針對不需要使用二級緩存的方法設置
useCache=false
<select id="selectOne" parameterType="java.lang.Integer" resultType="com.jimisun.domain.TestUser" useCache="false"> SELECT * from user where id = #{id} </select>
我們進行簡單的測試 , 觀察Mybatis二級緩存是否開啟
public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); TestUserMapper testUserMapper = (TestUserMapper) context.getBean("testUserMapper"); /*測試緩存:先查詢此時username為jimisun*/ TestUser testUser = testUserMapper.selectOne(1); /*測試緩存:修改username為lisi*/ Integer integer = testUserMapper.updateOne(1); /*測試緩存:最后查詢查看是否從數據庫獲取還是從緩存獲取*/ TestUser resultUser = testUserMapper.selectOne(1); System.out.println(resultUser.toString()); }
Mybatis其他使用技巧
- 在mapper.xml編寫sql時對於重復的sql我們可以使用<include refid="id">引用代碼
- 對於Mybatis非空判斷我們建議這樣使用 <if test="param !=null and param != ''">
- 一個Mapper.xml中可以直接引用另一個Mapper.xml的resultMap , 不需要重復定義
Java開發之上帝之眼系列教程其他文章
勘誤&感謝
本系列文章資料來源很多出自於互聯網和在下本身的見解,受限於個人技術能力水平和其他相關知識的限制,相關見解錯誤或者資料引用錯誤請各位幫助留言校正!引用資料多來自於互聯網,在下在引用前會遵循各位前輩或者博主的引用說明表示感謝,但互聯網資料多是轉發再轉發或存在遺漏請原作者內信聯系指正。