MyBatis-Spring(四)--MapperFactoryBean实现增删改查
上一篇文章中提到,使用SqlSessionTemplat時需要輸入一長串字符串來獲取mapper,這種方式IDE不會檢查程序的準確性并且很容易出錯,所以這篇文章介紹另一種可以避免這種問題,并且也可以使用SqlSessionTemplate的配置方式,那就是MyBatis-Spring團隊提供的MapperFactryBean類,通過這個類我們可以配置我們需要的mapper,并通過mapper的類型來獲取好,而不需要輸入一長串容易出錯的字符串。還是使用MyBatis-Spring項目的流程進行介紹:
第一步:創(chuàng)建spring-mybatis.xml文件并配置數(shù)據(jù)源
1 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 2 <property name="driverClassName" value="org.postgresql.Driver" /> 3 <property name="url" value="jdbc:postgresql://localhost:5433/postgres" /> 4 <property name="username" value="postgres" /> 5 <property name="password" value="postgres" /> 6 <!-- 最大數(shù)據(jù)庫連接數(shù) --> 7 <property name="maxActive" value="100" /> 8 <!-- 最大空閑數(shù),即等待連接數(shù) --> 9 <property name="maxIdle" value="5" /> 10 <!-- 最大等待連接時間 --> 11 <property name="maxWait" value="10000" /> 12 </bean>
第二步:配置SqlSessionFactory
1 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 2 <!-- 配置數(shù)據(jù)源 --> 3 <property name="dataSource" ref="dataSource" /> 4 <!-- 配置mybatis --> 5 <property name="configLocation" value="classpath:mybatis-config2.xml" /> 6 </bean>
上面的配置中,數(shù)據(jù)源屬性指向第一步中配置的dataSource,mybatis配置文件mybatis-config2.xml的內(nèi)容如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <!-- mybatis的基本配置文件:主要配置基本的上下文參數(shù)和運行環(huán)境 --> 6 <configuration> 7 <!--設置 --> 8 <settings> 9 <!--緩存配置的全局開關:如果這里設置成false,那么即便在映射器中配置開啟也無濟于事 --> 10 <setting name="cacheEnabled" value="true" /> 11 <!--延時加載的全局開關 --> 12 <setting name="lazyLoadingEnabled" value="false" /> 13 <!-- 是否允許單一語句返回多結(jié)果集 --> 14 <setting name="multipleResultSetsEnabled" value="false" /> 15 <!-- 使用列標簽代替列名,需要兼容驅(qū)動 --> 16 <setting name="useColumnLabel" value="true" /> 17 <!-- 允許JDBC自動生成主鍵,需要驅(qū)動兼容。如果設置為true,則這個設置強制使用自動生成主鍵,盡管一些驅(qū)動不能兼容但仍能正常工作 --> 18 <setting name="useGeneratedKeys" value="false" /> 19 <!-- 指定MyBatis該如何自動映射列到字段或?qū)傩?#xff1a;NONE表示取消自動映射;PARTIAL表示只會自動映射,沒有定義嵌套結(jié)果集和映射結(jié)果集;FULL會自動映射任意復雜的結(jié)果集,無論是否嵌套 --> 20 <setting name="autoMappingBehavior" value="PARTIAL" /> 21 <!-- 配置默認的執(zhí)行器:SIMPLE是普通的執(zhí)行器;REUSE會重用預處理語句;BATCH會重用語句并執(zhí)行批量更新 --> 22 <setting name="defaultExecutorType" value="SIMPLE" /> 23 <!--設置超時時間:它決定驅(qū)動等待數(shù)據(jù)庫響應的秒數(shù),任何正整數(shù) --> 24 <!-- <setting name="defaultStatementTimeout" value="25"/> --> 25 <!--設置數(shù)據(jù)庫驅(qū)動程序默認返回的條數(shù)限制,此參數(shù)可以重新設置,任何正整數(shù) --> 26 <!-- <setting name="defaultFetchSize" value="100" /> --> 27 <!-- 允許在嵌套語句中使用分頁(RowBounds) --> 28 <setting name="safeRowBoundsEnabled" value="false" /> 29 <!-- 是否開啟自動駝峰命名規(guī)則,即從a_example到aExample的映射 --> 30 <setting name="mapUnderscoreToCamelCase" value="true" /> 31 <!-- 本地緩存機制,防止循環(huán)引用和加速重復嵌套循環(huán) --> 32 <setting name="localCacheScope" value="SESSION" /> 33 <!-- 當沒有為參數(shù)提供特定JDBC類型時,為空值指定JDBC類型。某些驅(qū)動需要指定列的JDBC類型,多數(shù)情況直接用一般類型即可,如NULL/VARCHAR/OTHER --> 34 <setting name="jdbcTypeForNull" value="OTHER" /> 35 <!-- 指定觸發(fā)延遲加載的方法,如equals/clone/hashCode/toString --> 36 <setting name="lazyLoadTriggerMethods" value="equals" /> 37 </settings> 38 <!--類型命名 --> 39 <!--別名:pojo對象的別名 --> 40 <typeAliases> 41 <!-- 對包進行掃描,可以批量進行別名設置,設置規(guī)則是:獲取類名稱,將其第一個字母變?yōu)樾?--> 42 <package name="com.hyc.pojo" /> 43 <package name="com.hyc.objectfactory" /> 44 <package name="com.hyc.bean" /> 45 <package name="com.hyc.dao" /> 46 </typeAliases> 47 <!--插件 --> 48 <!-- <plugins /> --> 49 <!-- 映射器 --> 50 <mappers> 51 <mapper resource="com/hyc/mapper/ProductMapper.xml" /> 52 </mappers> 53 54 </configuration>
第三步:配置MapperFactoryBean
因為要使用MapperFactoryBean,這里的第三步為配置MapperFactoryBean,跟上一篇中介紹的配置SqlSessionTemplate是同一個步驟,不過上一篇中把它合并到第二步,這里覺得分開會比較清晰些:
1 <!-- 通過MapperFactoryBean配置SqlSessionFactory --> 2 <bean id="productMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 3 <!-- 配置mapper接口 --> 4 <property name="mapperInterface" value="com.hyc.dao.ProductMapper" /> 5 <!-- 配置SqlSessionFactory --> 6 <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 7 <!-- 如果同時配置sqlSessionTemplate和SqlSessionFactory,將優(yōu)先使用sqlSessionTemplate --> 8 <property name="sqlSessionTemplate" ref="sqlSessionTemplate" /> 9 </bean>
這個配置中有三個屬性可以配置:
- mapperInterface:它的值是*mapper.xml對應的接口,即映射器中的接口全限定名;
- sqlSessionFactory:就是第二步配置的SqlSessionFactory,包含的是數(shù)據(jù)源和sql文件;
- sqlSessionTemplate:上一篇文章中介紹過的配置,不再贅述;
注意??:如果同時配置sqlSessionFactory和sqlSessionTemplate,那么前者會被作廢,啟用后者,所以為了測試,可以將sqlSessionTemplate注釋掉。
第四步:創(chuàng)建mapper
其實就是創(chuàng)建映射器,分兩步:
1??創(chuàng)建接口
1 public interface ProductMapper { 2 3 int insertProduct(Product product); 4 5 int deleteByPrimaryKey(String id); 6 7 int updateByPrimaryKey(Product product); 8 9 List<Product> selectProducts(String name); 10 11 }
2??創(chuàng)建對應的mapper.xml(sql腳本文件)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 <mapper namespace="com.hyc.dao.ProductMapper"> 4 <resultMap id="BaseResultMap" type="com.hyc.pojo.Product"> 5 <id column="id" jdbcType="VARCHAR" property="id" /> 6 <result column="product_name" jdbcType="VARCHAR" property="productName" /> 7 <result column="product_price" jdbcType="VARCHAR" property="productPrice" /> 8 <result column="product_type" jdbcType="VARCHAR" property="productType" /> 9 </resultMap> 10 <sql id="Base_Column_List"> 11 id, product_name, product_price, product_type 12 </sql> 13 14 <!-- 查詢所有產(chǎn)品 --> 15 <select id="selectProducts" resultMap="BaseResultMap" parameterType="String"> 16 select * from product where product_name like concat('%',#{name},'%') 17 </select> 18 19 <!-- 插入產(chǎn)品 --> 20 <insert id="insertProduct" parameterType="com.hyc.pojo.Product"> 21 insert into product 22 (id, 23 product_name, product_price, 24 product_type) 25 values 26 (#{id,jdbcType=VARCHAR}, #{productName,jdbcType=VARCHAR}, 27 #{productPrice,jdbcType=VARCHAR}, 28 #{productType,jdbcType=VARCHAR}) 29 </insert> 30 31 <!-- 根據(jù)ID刪除產(chǎn)品 --> 32 <delete id="deleteByPrimaryKey" parameterType="java.lang.String"> 33 delete from 34 product 35 where id = #{id,jdbcType=VARCHAR} 36 </delete> 37 38 <!--修改產(chǎn)品 --> 39 <update id="updateByPrimaryKey" parameterType="com.hyc.pojo.Product"> 40 update product 41 set 42 product_name = #{productName,jdbcType=VARCHAR}, 43 product_price = 44 #{productPrice,jdbcType=VARCHAR}, 45 product_type = 46 #{productType,jdbcType=VARCHAR} 47 where id = #{id,jdbcType=VARCHAR} 48 </update> 49 </mapper>
它的命名空間就是對應接口的全限定名。
至此,所有的配置已經(jīng)完成,下面來創(chuàng)建單元測試類。
第五步:單元測試
1??創(chuàng)建一個基類,初始化spring配置
1 public class BaseTest { 2 3 public SqlSessionTemplate template = null; 4 ClassPathXmlApplicationContext context = null; 5 6 7 @Before 8 public void before() { 9 context = new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml"); 10 template = context.getBean(SqlSessionTemplate.class); 11 } 12 13 }
跟上一篇文章中創(chuàng)建的完全一樣
2??編寫測試方法
1 public class TestMapperFactoryBean extends BaseTest { 2 3 @Test 4 public void testInsert() { 5 ProductMapper pm = super.context.getBean(ProductMapper.class); 6 Product product = super.context.getBean(Product.class); 7 int add = pm.insertProduct(product); 8 System.out.println(add > 0 ? "插入成功" : "插入失敗"); 9 } 10 11 @Test 12 public void testDelete() { 13 ProductMapper pm = super.context.getBean(ProductMapper.class); 14 int del = pm.deleteByPrimaryKey("9b08ea56-6d92-48fc-844f-190eb6272479"); 15 System.out.println(del > 0 ? "刪除成功" : "刪除失敗"); 16 } 17 18 @Test 19 public void testUpdate() { 20 ProductMapper pm = super.context.getBean(ProductMapper.class); 21 Product product = super.context.getBean(Product.class); 22 product.setProductName("測試修改"); 23 product.setProductPrice("修改后價格"); 24 product.setProductType("修改后分類"); 25 int update = pm.updateByPrimaryKey(product); 26 System.out.println(update > 0 ? "修改成功" : "修改失敗"); 27 } 28 29 @Test 30 public void testSelect() { 31 ProductMapper pm = super.context.getBean(ProductMapper.class); 32 List<Product> pl = pm.selectProducts("T"); 33 System.out.println(pl.size()); 34 } 35 }
一個一個執(zhí)行,可進行測試,我的測試結(jié)果是都成功的,結(jié)果就不貼出來了。
這種方式有一個弊端,就是配置MapperFactoryBean時,mapper要一個一個進行配置,一個項目中的mapper肯定不止一個,所以這種配置難免會增加工作量,顯然不利于開發(fā),為此MyBatis提供了另一個類MapperScannerConfigurer,它可以通過掃描的形式去生成對應的mapper,而不需要我們一個一個配置。下一篇將介紹這種掃描配置方式的使用。
?
轉(zhuǎn)載于:https://www.cnblogs.com/hellowhy/p/9729181.html
總結(jié)
以上是生活随笔為你收集整理的MyBatis-Spring(四)--MapperFactoryBean实现增删改查的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 不孕不育几率多少
- 下一篇: Haproxy Nginx cluste