Document Version |
Development Tools |
Test Platform |
Project Name |
Date |
author |
Notes |
V1.0 |
|
|
|
2016.06.28 |
Lutianfei |
None |
Spring and MyBatis integration
Integration Ideas
- Spring is required to manage sqlsessionfactory in a single case.
- Spring and MyBatis Consolidate build proxy objects and use Sqlsessionfactory to create sqlsession. (Spring and MyBatis Integration Auto-complete)
- The mapper of the persistence layer needs to be managed by spring.
Integrated environment
- Create a new Java project (close to the actual development of the engineering structure)
Jar Package:
- MYBATIS3.2.7 's jar Package
- SPRING3.2.0 's jar Package
- MyBatis and Spring Integration packages: Early Ibatis and spring consolidation are provided by spring, and now mybatis and spring integration are provided by MyBatis.
- All jar packages (including SPRINGMVC)
Engineering structure
First step: Consolidate configuration sqlsessionfactory
- Configuring Sqlsessionfactory and data sources in Applicationcontext.xml
- Sqlsessionfactory is under the integration package for MyBatis and spring.
<!--load configuration files -- <context:property-placeholder location ="Classpath:db.properties" /> <!--data source, using 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="Ten" /> < property name="Maxidle" value="5" /> </Bean> <!--sqlsessinfactory -- <bean id= "sqlsessionfactory" class=" Org.mybatis.spring.SqlSessionFactoryBean "> <!--load MyBatis configuration file-- < property name="Configlocation" value="Mybatis/sqlmapconfig.xml" /> <!--data source - < property name="DataSource" ref="DataSource" /> </Bean>
Original DAO Development (and spring integration)
-
Sqlmap/user.xml
-
Load in Sqlmapconfig.xml user.xml
-
Dao ( Implement class inheritance Sqlsessiondaosupport)
-
Before the DAO interface implementation class needs to be injected sqlsessoinfactory, injected through spring.
-
Here's how to configure DAO's bean using Spring declaration configuration:
- let Userdaoimpl implement class inheritance Sqlsessiondaosupport
/li>
-
Configuring DAO
- Configuring the DAO interface in Applicationcontext.xml
<!-- 原始dao接口 --> <bean id="userDao" class="cn.itcast.ssm.dao.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean
- Test program
- Source_folder/userdaoimpltest.java
Public class userdaoimpltest { PrivateApplicationContext ApplicationContext;//In Setup This method gets the spring container @Before Public void setUp()throwsException {ApplicationContext =NewClasspathxmlapplicationcontext ("Classpath:spring/applicationcontext.xml"); }@Test Public void Testfinduserbyid()throwsException {Userdao Userdao = (Userdao) Applicationcontext.getbean ("Userdao");//method of calling UserdaoUser user = Userdao.finduserbyid (1); SYSTEM.OUT.PRINTLN (user); }}
Mapper Agent Development
mapper scanning via Mapperscannerconfigurer(recommended)
* basePackage
After configuring the Mapper scan path through the properties, the scan path is not configured in Sqlmapperconfig.xml.
Reverse Engineering
Mybaits requires programmers to write their own SQL statements, MyBatis official reverse engineering can be automatically generated for a single table MyBatis execute the required code (mapper.java,mapper.xml, PO. )
In the enterprise actual development, the commonly used reverse engineering way: Because the database table generates the Java code.
Download Reverse Engineering
How to use(Will be used)
<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> <!--whether to remove automatically generated comments true: Yes: false: No -- < property name="suppressallcomments" value="true" /> </commentgenerator> <!--database connection information: Driver class, connection address, user name, password- - <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> -- <!--default False to parse the JDBC decimal and NUMERIC types to Integer, and to resolve the JDBC decimal and NUMERIC types to Java.math.BigDec when True iMAL -- <javatyperesolver> < property name="Forcebigdecimals" value="false" /> </javatyperesolver> <!--targetproject: Generate POS Class Location-- <javamodelgenerator targetpackage="Cn.itcast.ssm.po"targetproject= ". \src"> <!--enablesubpackages: Do you want the schema to be a suffix of the package-- < property name="Enablesubpackages" value="false" / > <!--The value returned from the database is cleared before and after the space- < property name="trimstrings" value="true" /> </javamodelgenerator> <!--targetproject:mapper Map file generated location-- <sqlmapgenerator targetpackage="Cn.itcast.ssm.mapper"targetproject =". \src"> <!--enablesubpackages: Do you want the schema to be a suffix of the package-- < property name="Enablesubpackages" value="false" /> </sqlmapgenerator> <!--Targetpackage:mapper interface generated location-- <javaclientgenerator type= "xmlmapper"targetpackage=" Cn.itcast.ssm.mapper "targetproject=". \src "> <!--enablesubpackages: Do you want the schema to be a suffix of the package-- < property name="Enablesubpackages" value="false" /> </javaclientgenerator> <!--specifying database tables -- <table tableName="items"></table> <table tableName="Orders"></table> <table tableName="OrderDetail"></table> <table tableName="user"></table> </Context></generatorconfiguration>
using the generated code
//Custom condition Query @Test Public void Testselectbyexample() {Itemsexample itemsexample =NewItemsexample ();//Construct query criteria through criteriaItemsexample.criteria Criteria = Itemsexample.createcriteria (); Criteria.andnameequalto ("Notebook 3");//May return more than one recordlist<items> list = Itemsmapper.selectbyexample (itemsexample); SYSTEM.OUT.PRINTLN (list); }//Search by primary key @Test Public void Testselectbyprimarykey() {Items items = Itemsmapper.selectbyprimarykey (1); SYSTEM.OUT.PRINTLN (items); }//Insert @Test Public void Testinsert() {//Construct Items ObjectItems items =NewItems (); Items.setname ("mobile"); Items.setprice (999f); Itemsmapper.insert (items); }//Update data @Test Public void Testupdatebyprimarykey() {//Update all fields, need to be queried before updatingItems items = Itemsmapper.selectbyprimarykey (1); Items.setname ("Water Cup"); Itemsmapper.updatebyprimarykey (items);//If the incoming field is not empty to update, use this method in a bulk update and do not need to query and update first //itemsmapper.updatebyprimarykeyselective (record);}
MyBatis Entry 2nd day--mybatis and Spring integration and reverse engineering