spring和mybatis整合
整合思路
需要spring通過單例方式管理SqlSessionFactory。
spring和mybatis整合組建代理程式對象,使用SqlSessionFactory建立SqlSession。(spring和mybatis整合自動完成)
持久層的mapper都需要由spring進行管理。
整合環境
建立一個新的java工程(接近實際開發的工程結構)
jar包:
mybatis3.2.7的jar包
spring3.2.0的jar包
mybatis和spring的整合包:早期ibatis和spring整合是由spring官方提供,現在mybatis和spring整合由mybatis提供。
全部jar包(含springmvc)
工程結構
第一步:整合配置sqlSessionFactory
在applicationContext.xml配置sqlSessionFactory和資料來源
sqlSessionFactory在mybatis和spring的整合包下。
<!-- 載入設定檔 --><context:property-placeholder location="classpath:db.properties" /><!-- 資料來源,使用dbcp --><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"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" /><property name="maxIdle" value="5" /></bean><!-- sqlSessinFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 載入mybatis的設定檔 --><property name="configLocation" value="mybatis/SqlMapConfig.xml" /><!-- 資料來源 --><property name="dataSource" ref="dataSource" /></bean>
原始dao開發(和spring整合後)
sqlmap/User.xml
在SqlMapconfig.xml中載入User.xml
dao(實作類別繼承SqlSessionDaoSupport)
之前dao介面實作類別需要注入SqlSessoinFactory,通過spring進行注入。
這裡使用spring聲明配置方式,配置dao的bean:
讓UserDaoImpl實作類別繼承SqlSessionDaoSupport
配置dao
在applicationContext.xml中配置dao介面
<!-- 原始dao介面 --><bean id="userDao" class="cn.itcast.ssm.dao.UserDaoImpl"><property name="sqlSessionFactory" ref="sqlSessionFactory"/></bean>
測試程式
source_folder/UserDaoImplTest.javapublic class UserDaoImplTest {private ApplicationContext applicationContext;//在setUp這個方法得到spring容器@Beforepublic void setUp() throws Exception {applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");}@Testpublic void testFindUserById() throws Exception {UserDao userDao = (UserDao) applicationContext.getBean("userDao");//調用userDao的方法User user = userDao.findUserById(1);System.out.println(user);}}
mapper代理開發
Usermapper.xml和Usermapper.java
將之前工程中拷貝過來刪改包路徑即可。
通過MapperFactoryBean建立代理對象
因為UserMapper不是介面類型,所以要用MapperFactoryBean來產生介面類型
此方法問題:
需要針對每個mapper進行配置,麻煩。
通過MapperScannerConfigurer進行mapper掃描(建議使用)
* 這裡通過basePackage屬性配置了mapper的掃描路徑後,在SqlMapperConfig.xml中就不用配置掃描路徑了。
這裡使用sqlSessionFactoryBeanName屬性是因為如果配置的是sqlSessionFactory屬性,將不會先載入資料庫設定檔及資料來源配置(db.properties)
測試代碼
逆向工程
mybaits需要程式員自己編寫sql語句,mybatis官方提供逆向工程 可以針對單表自動產生mybatis執行所需要的代碼(mapper.java,mapper.xml、po..)
企業實際開發中,常用的逆向工程方式:由於資料庫的表產生java代碼。
下載逆向工程
使用方法(會用)運行逆向工程
建議使用java程式方式,不依賴開發工具。
產生代碼設定檔(有4處需要修改的地方)
產生PO類的位置 : cn.itcast.ssm.po
mapper對應檔產生的位置 : cn.itcast.ssm.mapper
mapper介面產生的位置 : cn.itcast.ssm.mapper
指定資料庫表:
<table tableName="items"></table><table tableName="orders"></table><table tableName="orderdetail"></table><table tableName="user"></table><?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><context id="testTables" targetRuntime="MyBatis3"><commentGenerator><!-- 是否去除自動產生的注釋 true:是 : false:否 --><property name="suppressAllComments" value="true" /></commentGenerator><!--資料庫連接的資訊:驅動類、串連地址、使用者名稱、密碼 --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root"password="mysql"></jdbcConnection><!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" userId="yycg"password="yycg"></jdbcConnection> --><!-- 預設false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer,為 true時把JDBC DECIMAL 和 NUMERIC 類型解析為java.math.BigDecimal --><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><!-- targetProject:產生PO類的位置 --><javaModelGenerator targetPackage="cn.itcast.ssm.po"targetProject=".\src"><!-- enableSubPackages:是否讓schema作為包的尾碼 --><property name="enableSubPackages" value="false" /><!-- 從資料庫返回的值被清理前後的空格 --><property name="trimStrings" value="true" /></javaModelGenerator><!-- targetProject:mapper對應檔產生的位置 --><sqlMapGenerator targetPackage="cn.itcast.ssm.mapper" targetProject=".\src"><!-- enableSubPackages:是否讓schema作為包的尾碼 --><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- targetPackage:mapper介面產生的位置 --><javaClientGenerator type="XMLMAPPER"targetPackage="cn.itcast.ssm.mapper" targetProject=".\src"><!-- enableSubPackages:是否讓schema作為包的尾碼 --><property name="enableSubPackages" value="false" /></javaClientGenerator><!-- 指定資料庫表 --><table tableName="items"></table><table tableName="orders"></table><table tableName="orderdetail"></table><table tableName="user"></table></context></generatorConfiguration>
執行產生程式
產生後的代碼
使用產生的程式碼
需要將產生工程中所產生的程式碼拷貝到自己的工程中。
測試ItemsMapper中的方法
//自訂條件查詢@Testpublic void testSelectByExample() {ItemsExample itemsExample = new ItemsExample();//通過criteria構造查詢條件ItemsExample.Criteria criteria = itemsExample.createCriteria();criteria.andNameEqualTo("筆記本3");//可能返回多條記錄List<Items> list = itemsMapper.selectByExample(itemsExample);System.out.println(list);}//根據主鍵查詢@Testpublic void testSelectByPrimaryKey() {Items items = itemsMapper.selectByPrimaryKey(1);System.out.println(items);}//插入@Testpublic void testInsert() {//構造 items對象Items items = new Items();items.setName("手機");items.setPrice(999f);itemsMapper.insert(items);}//更新資料@Testpublic void testUpdateByPrimaryKey() {//對所有欄位進行更新,需要先查詢出來再更新Items items = itemsMapper.selectByPrimaryKey(1);items.setName("水杯");itemsMapper.updateByPrimaryKey(items);//如果傳入欄位不空為才更新,在批次更新中使用此方法,不需要先查詢再更新//itemsMapper.updateByPrimaryKeySelective(record);}
以上所述是小編給大家介紹的淺析Spring和MyBatis整合及逆向工程,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!