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的整合包下。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<!-- 加載配置文件 --> <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接口
1
2
3
4
|
<!-- 原始dao接口 --> <bean id= "userDao" class = "cn.itcast.ssm.dao.UserDaoImpl" > <property name= "sqlSessionFactory" ref= "sqlSessionFactory" /> </bean> |
測試程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
source_folder/UserDaoImplTest.java public class UserDaoImplTest { private ApplicationContext applicationContext; //在setUp這個方法得到spring容器 @Before public void setUp() throws Exception { applicationContext = new ClassPathXmlApplicationContext( "classpath:spring/applicationContext.xml" ); } @Test public 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
指定數據庫表:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
<table tableName= "items" ></table> <table tableName= "orders" ></table> <table tableName= "orderdetail" ></table> <table tableName= "user" ></table> <?xml version= "1.0" encoding= "UTF-8" ?> <!DOCTYPE generatorConfiguration PUBLIC "-//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中的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
//自定義條件查詢 @Test public 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); } //根據主鍵查詢 @Test public void testSelectByPrimaryKey() { Items items = itemsMapper.selectByPrimaryKey( 1 ); System.out.println(items); } //插入 @Test public void testInsert() { //構造 items對象 Items items = new Items(); items.setName( "手機" ); items.setPrice(999f); itemsMapper.insert(items); } //更新數據 @Test public void testUpdateByPrimaryKey() { //對所有字段進行更新,需要先查詢出來再更新 Items items = itemsMapper.selectByPrimaryKey( 1 ); items.setName( "水杯" ); itemsMapper.updateByPrimaryKey(items); //如果傳入字段不空為才更新,在批量更新中使用此方法,不需要先查詢再更新 //itemsMapper.updateByPrimaryKeySelective(record); } |
以上所述是小編給大家介紹的淺析Spring和MyBatis整合及逆向工程,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/lutianfeiml/article/details/51781389