淺析Spring和MyBatis整合及逆向工程
spring和mybatis整合
整合思路
需要spring通過單例方式管理SqlSessionFactory。
spring和mybatis整合生成代理對象,使用SqlSessionFactory創(chuàng)建SqlSession。(spring和mybatis整合自動完成)
持久層的mapper都需要由spring進行管理。
整合環(huán)境
創(chuàng)建一個新的java工程(接近實際開發(fā)的工程結(jié)構(gòu))
jar包:
mybatis3.2.7的jar包
spring3.2.0的jar包
mybatis和spring的整合包:早期ibatis和spring整合是由spring官方提供,現(xiàn)在mybatis和spring整合由mybatis提供。
全部jar包(含springmvc)
工程結(jié)構(gòu)
第一步:整合配置sqlSessionFactory
在applicationContext.xml配置sqlSessionFactory和數(shù)據(jù)源
sqlSessionFactory在mybatis和spring的整合包下。
<!-- 加載配置文件 --> <context:property-placeholder location="classpath:db.properties" /> <!-- 數(shù)據(jù)源,使用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" /> <!-- 數(shù)據(jù)源 --> <property name="dataSource" ref="dataSource" /> </bean>
原始dao開發(fā)(和spring整合后)
sqlmap/User.xml
在SqlMapconfig.xml中加載User.xml
dao(實現(xiàn)類繼承SqlSessionDaoSupport)
之前dao接口實現(xiàn)類需要注入SqlSessoinFactory,通過spring進行注入。
這里使用spring聲明配置方式,配置dao的bean:
讓UserDaoImpl實現(xiàn)類繼承SqlSessionDaoSupport
配置dao
在applicationContext.xml中配置dao接口
<!-- 原始dao接口 --> <bean id="userDao" class="cn.itcast.ssm.dao.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>
測試程序
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"); //調(diào)用userDao的方法 User user = userDao.findUserById(1); System.out.println(user); } }
mapper代理開發(fā)
Usermapper.xml和Usermapper.java
將之前工程中拷貝過來刪改包路徑即可。
通過MapperFactoryBean創(chuàng)建代理對象
因為UserMapper不是接口類型,所以要用MapperFactoryBean來生成接口類型
此方法問題:
需要針對每個mapper進行配置,麻煩。
通過MapperScannerConfigurer進行mapper掃描(建議使用)
* 這里通過basePackage屬性配置了mapper的掃描路徑后,在SqlMapperConfig.xml中就不用配置掃描路徑了。
這里使用sqlSessionFactoryBeanName屬性是因為如果配置的是sqlSessionFactory屬性,將不會先加載數(shù)據(jù)庫配置文件及數(shù)據(jù)源配置(db.properties)
測試代碼
逆向工程
mybaits需要程序員自己編寫sql語句,mybatis官方提供逆向工程 可以針對單表自動生成mybatis執(zhí)行所需要的代碼(mapper.java,mapper.xml、po..)
企業(yè)實際開發(fā)中,常用的逆向工程方式:由于數(shù)據(jù)庫的表生成java代碼。
下載逆向工程
使用方法(會用)運行逆向工程
建議使用java程序方式,不依賴開發(fā)工具。
生成代碼配置文件(有4處需要修改的地方)
生成PO類的位置 : cn.itcast.ssm.po
mapper映射文件生成的位置 : cn.itcast.ssm.mapper
mapper接口生成的位置 : cn.itcast.ssm.mapper
指定數(shù)據(jù)庫表:
<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> <!--數(shù)據(jù)庫連接的信息:驅(qū)動類、連接地址、用戶名、密碼 --> <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" /> <!-- 從數(shù)據(jù)庫返回的值被清理前后的空格 --> <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> <!-- 指定數(shù)據(jù)庫表 --> <table tableName="items"></table> <table tableName="orders"></table> <table tableName="orderdetail"></table> <table tableName="user"></table> </context> </generatorConfiguration>
執(zhí)行生成程序
生成后的代碼
使用生成的代碼
需要將生成工程中所生成的代碼拷貝到自己的工程中。
測試ItemsMapper中的方法
//自定義條件查詢 @Test public void testSelectByExample() { ItemsExample itemsExample = new ItemsExample(); //通過criteria構(gòu)造查詢條件 ItemsExample.Criteria criteria = itemsExample.createCriteria(); criteria.andNameEqualTo("筆記本3"); //可能返回多條記錄 List<Items> list = itemsMapper.selectByExample(itemsExample); System.out.println(list); } //根據(jù)主鍵查詢 @Test public void testSelectByPrimaryKey() { Items items = itemsMapper.selectByPrimaryKey(1); System.out.println(items); } //插入 @Test public void testInsert() { //構(gòu)造 items對象 Items items = new Items(); items.setName("手機"); items.setPrice(999f); itemsMapper.insert(items); } //更新數(shù)據(jù) @Test public void testUpdateByPrimaryKey() { //對所有字段進行更新,需要先查詢出來再更新 Items items = itemsMapper.selectByPrimaryKey(1); items.setName("水杯"); itemsMapper.updateByPrimaryKey(items); //如果傳入字段不空為才更新,在批量更新中使用此方法,不需要先查詢再更新 //itemsMapper.updateByPrimaryKeySelective(record); }
以上所述是小編給大家介紹的淺析Spring和MyBatis整合及逆向工程,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
spring的構(gòu)造函數(shù)注入屬性@ConstructorBinding用法
這篇文章主要介紹了關(guān)于spring的構(gòu)造函數(shù)注入屬性@ConstructorBinding用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12SpringBoot快速設置攔截器并實現(xiàn)權(quán)限驗證的方法
本篇文章主要介紹了SpringBoot快速設置攔截器并實現(xiàn)權(quán)限驗證的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01Java使用JCommander實現(xiàn)解析命令行參數(shù)
jcommander?是一個只有幾十?kb?的?Java?命令行參數(shù)解析工具,可以通過注解的方式快速實現(xiàn)命令行參數(shù)解析,本文就來和大家介紹一下JCommander是如何解析命令行參數(shù)吧2023-06-06如何在SpringBoot 中使用 Druid 數(shù)據(jù)庫連接池
這篇文章主要介紹了SpringBoot 中使用 Druid 數(shù)據(jù)庫連接池的實現(xiàn)步驟,幫助大家更好的理解和學習使用SpringBoot,感興趣的朋友可以了解下2021-03-03Spring Boot中整合Spring Security并自定義驗證代碼實例
本篇文章主要介紹了Spring Boot中整合Spring Security并自定義驗證代碼實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04