Spring and MyBatis Consolidation
Integration Ideas
Spring needs to be managed sqlsessionfactory through a single example.
Spring and MyBatis Consolidate build proxy objects and create sqlsession using Sqlsessionfactory. (Spring and MyBatis consolidation is done automatically)
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 Jar Pack
spring3.2.0 Jar Pack
Consolidation packages for MyBatis and spring: Early Ibatis and spring consolidation were provided by the spring authorities, and now mybatis and spring consolidation are provided by MyBatis.
All jar packages (including SPRINGMVC)
Engineering structure
The first step: the integration of configuration Sqlsessionfactory
Configuring Sqlsessionfactory and data sources in Applicationcontext.xml
Sqlsessionfactory is under the integration package of MyBatis and spring.
<!--load configuration file-->
<context:property-placeholder location= "classpath:db.properties"/>
<!--data source , using the 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 (after spring consolidation)
Sqlmap/user.xml
Loading User.xml in Sqlmapconfig.xml
DAO (Implementation class inherits Sqlsessiondaosupport)
Before the DAO interface implementation class needs to inject sqlsessoinfactory and inject it through spring.
Here you configure the DAO's bean using the Spring Declaration configuration method:
Let Userdaoimpl implement class inheritance Sqlsessiondaosupport
Configure DAO
To configure the DAO interface in Applicationcontext.xml
<!--original DAO interface-->
<bean id= "Userdao" class= "Cn.itcast.ssm.dao.UserDaoImpl" >
<property name= " Sqlsessionfactory "ref=" sqlsessionfactory "/>
</bean>
Test program
Source_folder/userdaoimpltest.java public
class Userdaoimpltest {
private ApplicationContext ApplicationContext;
In Setup this method gets the spring container
@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");
Call Userdao method
User user = Userdao.finduserbyid (1);
SYSTEM.OUT.PRINTLN (user);
}
Mapper Agent Development
Usermapper.xml and Usermapper.java
Copy the previous project to remove the package path.
To create a proxy object from Mapperfactorybean
Because Usermapper is not an interface type, you use Mapperfactorybean to generate an interface type
This method issue:
Need to be configured for each mapper, trouble.
Mapper scanning via Mapperscannerconfigurer (recommended)
* Here, after configuring the Mapper scan path with the Basepackage property, the scan path is not configured in Sqlmapperconfig.xml.
The Sqlsessionfactorybeanname property is used here because if the Sqlsessionfactory property is configured, the database configuration file and the data source configuration (db.properties) will not be loaded first
Test code
Reverse engineering
Mybaits need programmers to write their own SQL statements, mybatis the official provision of reverse engineering can automatically generate MyBatis execution for a single table code (mapper.java,mapper.xml, Po ... )
In the actual development of enterprises, the commonly used reverse engineering way: Because the table of the database generates Java code.
Download Reverse Engineering
Use method (used) to run reverse engineering
It is recommended that you use Java programs without relying on development tools.
Generate Code Profiles (4 places to modify)
Build PO class Location: Cn.itcast.ssm.po
Mapper Map File generated location: Cn.itcast.ssm.mapper
Mapper Interface generated location: Cn.itcast.ssm.mapper
To specify a database table:
<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 Mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <generatorConfiguration> <context id=" Testtables " Targetruntime= "MyBatis3" > <commentGenerator> <!--whether to remove automatically generated comments true: false: No--> <property name= " Suppressallcomments "value=" true "/> </commentGenerator> <!--database connection information: Driver class, connection address, username, password--> < Jdbcconnection driverclass= "Com.mysql.jdbc.Driver" connectionurl= "Jdbc:mysql://localhost:3306/mybatis" 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 resolve JDBC decimal and NUMERIC types to Integer, and JDBC decimal and NUMERIC when True
Type resolution is Java.math.BigDecimal--> <javaTypeResolver> <property name= "Forcebigdecimals" value= "false"/> </javaTypeResolver> <!--targetproject: Generate PO class location--> <javamodelgenerator targetpackage= " Cn.itcast.ssm.po "targetproject=". \src "> <!--enablesubpackages: Let schema be the suffix of the package--> <property name=" Enablesubpackages "value= false"/> <!--the space before and after the value returned from the database is cleaned--> <property name= "trimstrings" value= "true"/ > </javaModelGenerator> <!--targetproject:mapper mapping file generated location--> <sqlmapgenerator targetpackage= " Cn.itcast.ssm.mapper "targetproject=". \src "> <!--enablesubpackages: Let schema be the suffix of the package--> <property name=" Enablesubpackages "value=" false "/> </sqlMapGenerator> <!--targetpackage:mapper interface generated location--> < Javaclientgenerator type= "Xmlmapper" targetpackage= "Cn.itcast.ssm.mapper". \src "> <!--enablesubpackages: Let schema be the suffix of the package--> <property name=" Enablesubpackages "value=" false "/> </javaClientGenerator> <!--Specify database table--> <table tablename= "items" ></table> <table tablename= "Orders" ></table> <table tablename= "OrderDetail" ></table> <table tablename= "user" ></ Table> </context> </generatorConfiguration>
Executing the Build Program
Post-generated code
Using the generated code
The code generated in the build project needs to be copied into its own project.
Testing the methods in Itemsmapper
//Custom conditional query @Test public void Testselectbyexample () {itemsexample itemsexample = new Item
Sexample ();
Construct a query condition through criteria itemsexample.criteria criteria = Itemsexample.createcriteria ();
Criteria.andnameequalto ("Notebook 3");
May return more than one record list<items> List = Itemsmapper.selectbyexample (itemsexample);
SYSTEM.OUT.PRINTLN (list);
@Test public void Testselectbyprimarykey () {The Items items = Itemsmapper.selectbyprimarykey (1) According to the primary key query;
SYSTEM.OUT.PRINTLN (items);
}//Insert @Test public void Testinsert () {//construct items Objects items = new items (); Items.setname ("mobile"); Items.setprice (999f);
Itemsmapper.insert (items); }//Update data @Test public void Testupdatebyprimarykey () {//Update all fields, need to query and update the items = Itemsmapper.selectbyprimarykey
(1);
Items.setname ("Water cup");
Itemsmapper.updatebyprimarykey (items);
If the incoming field is not empty to update, use this method in batch update, do not need to query before updating//itemsmapper.updatebyprimarykeyselective (record); }
The above is a small series to introduce the analysis of spring and MyBatis integration and reverse engineering, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!