"MyBatis framework" mybatis and spring consolidation _mybatis

Source: Internet
Author: User
Tags aop pack
Spring and MyBatis Consolidation

1. 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.

2. 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 spring authorities, MyBatis and spring consolidation provided by MyBatis. Jar Package Name Mybatis-spring-1.2.2.jar

Add MyBatis to all jar packages with spring consolidation

As shown in figure



Engineering Structure:

As shown in figure




3.sqlSessionFactory
Configure sqlsessionfactory and data sources

in Applicationcontext.xml Sqlsessionfactory is under the integration package of MyBatis and spring.

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc= "Http://www.springframework.org/schema/mvc" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi:schemalocation= "http://www.springframework.org/schema/ 
		Beans Http://www.springframework.org/schema/beans/spring-beans-3.2.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd Http://www.springframework.org/schema/context http ://www.springframework.org/schema/context/spring-context-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http ://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http:// Www.springframework.org/schema/tx/spring-tx-3.2.xsd > <!--load configuration file--> <Context:property-placeholder location= "Classpath:db.properties"/> <!--data source using DBCP--> <bean id= "Datasour Ce "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= "${j" Dbc.username} "/> <property name=" password "value=" ${jdbc.password} "/> <property name=" maxActive "value=" "/> <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= "da Tasource "/> </bean> </beans>

4. Original DAO development (after spring integration)
4.1user.xml
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE Mapper Public
"-//mybatis.org//dtd mapper 3.0//en"
"HTTP://MYBATIS.ORG/DTD/MYBATIS-3-MAPPER.DTD" >


<!--namespace namespace, the role is to classify SQL management, understand the SQL isolation
Note: The use of Mapper agent method development, namespace has a special important role-->
< Mapper namespace= "Test" >
	<!--Configure many SQL statements in the mapping file-->
	
	<!--requirements: Querying user table records by ID-->
	<!-- Execute database query by select
	     ID: Mark SQL in mapping file, become statement ID to 
	     encapsulate SQL statements into Mappedstatement objects, so ID is called statement ID,
	     
	     ParameterType: Specifies the type of input parameter,
	     
	     #{} identifies a placeholder,
	     
	     #{id} where the ID represents the name of the input parameter, and if the input parameter is a simple type, the value in #{} can be arbitrary (for example, value).
	     
	     Resulttype: Specifies the Java object type for the mapping of the SQL output results,
	     Select Specifies that Resulttype represents a single record mapped to a Java object-->	
	<select id= " Finduserbyid "parametertype=" int "resulttype=" Cn.edu.hpu.ssm.po.User ">
	  SELECT * from User WHERE Id=#{id}
	</select>
	
</mapper>

Loading User.xml in Sqlmapconfig.xml
<!--load mapping file-->
<mappers>
	<!--load one mapping file at a time by resource method-->
	<mapper resource= "Sqlmap /user.xml "/>
	
	<!--bulk load mapper-->
	<package name=" Cn.edu.hpu.ssm.mapper "/>
</mappers >

4.2dao (Implementation class inherits Sqlsessiondaosupport)


The DAO interface implementation class needs to inject sqlsessoinfactory and inject it through spring.
Here spring declares the configuration method, configuring the DAO Bean:

Let Userdaoimpl implement class inheritance Sqlsessiondaosupport

4.3 Configuring DAO
First create Userdao interface and Userdaoimpl interface implementation
Userdao.java:

Package Cn.edu.hpu.ssm.dao;

Import Cn.edu.hpu.ssm.po.User;

User-Managed DAO interface Public
interface userdao{
	
	//query user information based on ID public user
	finduserbyid (int id) throws Exception;
}

Userdaoimpl.java:
Package Cn.edu.hpu.ssm.dao;

Import org.apache.ibatis.session.SqlSession;
Import org.apache.ibatis.session.SqlSessionFactory;

Import Cn.edu.hpu.ssm.po.User;

public class Userdaoimpl implements userdao{


	//needs to be injected into the DAO implementation class Sqlsessionfactory factory//
	Here we are temporarily unused spring, we inject
	private sqlsessionfactory sqlsessionfactory;
	Public Userdaoimpl (Sqlsessionfactory sqlsessionfactory) {
		this.sqlsessionfactory=sqlsessionfactory;
	}


	Public User Finduserbyid (int id) throws Exception {
		sqlsession sqlsession=sqlsessionfactory.opensession ();
		
		User User=sqlsession.selectone ("Test.finduserbyid", id);
		
		Releasing Resources
		Sqlsession.close ();
		return user;
	}

Configure DAO in Applicationcontext.xml.
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc= "Http://www.springframework.org/schema/mvc" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi:schemalocation= "http://www.springframework.org/schema/ 
		Beans Http://www.springframework.org/schema/beans/spring-beans-3.2.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd Http://www.springframework.org/schema/context http ://www.springframework.org/schema/context/spring-context-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http ://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http:// Www.springframework.org/schema/tx/spring-tx-3.2.xsd > <!--load configuration file--> <Context:property-placeholder location= "Classpath:db.properties"/> <!--data source using DBCP--> <bean id= "Datasour Ce "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= "${j" Dbc.username} "/> <property name=" password "value=" ${jdbc.password} "/> <property name=" maxActive "value=" "/> <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= "da 
		Tasource "/> </bean> <!--original DAO interface--> <bean id=" Userdao "class=" Cn.edu.hpu.ssm.dao.UserDaoImpl "> <property name= "SqlsessioNfactory "ref=" sqlsessionfactory "></property> </bean> </beans> 

Let Userdaoimpl inherit the Sqlsessiondaosupport class and provide set and Getsqlsessionfactory methods in the Sqlsessiondaosupport class.
Package Cn.edu.hpu.ssm.dao;

Import org.apache.ibatis.session.SqlSession;
Import Org.mybatis.spring.support.SqlSessionDaoSupport;


Import Cn.edu.hpu.ssm.po.User;


public class Userdaoimpl extends Sqlsessiondaosupport implements userdao{public


	User Finduserbyid (int id) throws exc eption {
		//Inherit Sqlsessiondaosupport class, Get sqlsession sqlsession via This.getsqlsession ()
		sqlsession= This.getsqlsession ();
		
		User User=sqlsession.selectone ("Test.finduserbyid", id);
		
		return user;
	}

4.4 Test Program
Package cn.edu.hpu.ssm.test;

Import Org.junit.Before;
Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;


Import Cn.edu.hpu.ssm.dao.UserDao;
Import Cn.edu.hpu.ssm.po.User;


public class Userdaoimpltest {
	
	private applicationcontext applicationcontext;
	
	Note Before call this method before executing all of the test methods in this class
	@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);
		Output user Information
		System.out.println (User.getid () + ":" +user.getusername ());
	}
	

Test results and output logs:
debug [main]-Creating a new sqlsession
debug [main]-sqlsession [ ORG.APACHE.IBATIS.SESSION.DEFAULTS.DEFAULTSQLSESSION@8DCD5D] is not registered for synchronization because Synchronization is isn't active
debug [main]-fetching JDBC Connection from DataSource
Debug [main]-JDBC Connecti On [Jdbc:mysql://localhost:3306/mybatis?characterencoding=utf-8, Username=root@localhost, MySQL-AB JDBC Driver] would Not is managed by Spring
DEBUG [main]-==> preparing:select * from USER WHERE id=? 
debug [main]-==> parameters:1 (Integer)
Debug [main]-<== total:1
Debug [main]-Closing non transaction Al sqlsession [org.apache.ibatis.session.defaults.defaultsqlsession@8dcd5d]
DEBUG [main]-Returning JDBC Connection to DataSource
1: Ms Cheung

5.mapper Agent Development
5.1mapper.xml and Mapper.java
Usermapper.xml:
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE Mapper Public
"-//mybatis.org//dtd mapper 3.0//en"
"HTTP://MYBATIS.ORG/DTD/MYBATIS-3-MAPPER.DTD" >


<mapper namespace= "Cn.edu.hpu.ssm.mapper.UserMapper" >
	
	<select id= "Finduserbyid" parametertype= "int" resulttype= "Cn.edu.hpu.mybatis.po.User" >
	  SELECT * from User WHERE id=#{id}
	</ Select>
	
</mapper>

Usermapper.java:
Package cn.edu.hpu.ssm.mapper;

Import Cn.edu.hpu.ssm.po.User;

User-Managed DAO interface Public
interface Usermapper {
	
	//query user information based on ID public user
	finduserbyid (int id) throws Exception;
}

5.2 Creating proxy objects through Mapperfactorybean
<!--mapper configuration 
	Mapperfactorybean generates mapper proxy objects based on the Mapper interface--> <bean id= "
	usermapper" Org.mybatis.spring.mapper.MapperFactoryBean ">
		<!--mapperinterface Specify Mapper interface-->
		<property Name= "Mapperinterface" value= "Cn.edu.hpu.ssm.mapper.UserMapper"/> <property name=
		"Sqlsessionfactory" ref= "Sqlsessionfactory"/>
	</bean>

This method issue:
Need to be configured for each mapper, trouble. So we have to do mapper scanning through mapperscannerconfigurer.

5.3 Mapper scanning via Mapperscannerconfigurer (recommended)
<!--Mapper Bulk scans, scanning the Mapper interface from the Mapper package, automatically creating proxy objects and injecting adherence specifications into the spring container 
	: Keep the Mapper.java and Mapper.xml map file names consistent and in a directory.
	The ID of the mapper bean automatically scanned is mapper class name (first lowercase)-->
<bean class= " Org.mybatis.spring.mapper.MapperScannerConfigurer >
	<!--Specify which package names are scanned
	if multiple packages are scanned, a half-width comma is used in the middle of each packet to separate-->
	<property name= "Basepackage" value= "Cn.edu.hpu.ssm.mapper"/> <property name=
	" Sqlsessionfactorybeanname "value=" sqlsessionfactory "></property>
</bean>

The mapper scan in the sqlmapperconfig.xml will not be allowed.
<!--load mapping file-->
<mappers>
	<!--load one mapping file at a time by resource method-->
	<mapper resource= " Sqlmap/user.xml "/>
	
	<!--bulk Load mapper
		
	and spring integration, using the Mapper scanner, there is no need to configure-->
	<!--< Package Name= "Cn.edu.hpu.ssm.mapper"/>-->
</mappers>

5.4 Test Code
Package cn.edu.hpu.ssm.test;

Import Org.junit.Before;
Import Org.junit.Test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;


Import Cn.edu.hpu.ssm.mapper.UserMapper;
Import Cn.edu.hpu.ssm.po.User;


public class Usermappertest {


private applicationcontext applicationcontext;
	
	Note Before call this method before executing all of the test methods in this class
	@Before public
	Void Setup () throws exception{
		applicationcontext=new Classpathxmlapplicationcontext ("Classpath:spring/applicationcontext.xml");
		
	}
	
	@Test public
	void Testfinduserbyid () throws Exception {
		usermapper usermapper= (usermapper) Applicationcontext.getbean ("Usermapper");
		User User=usermapper.finduserbyid (1);
		System.out.println (User.getid () + ":" +user.getusername ());
		
	}


}

Test results and output log:

debug [main]-Returning cached instance of singleton Bean ' usermapper '
debug [main]-Creating a new sqlsession
D Ebug [main]-sqlsession [org.apache.ibatis.session.defaults.defaultsqlsession@13b5a3a] is not registered for Synchronization because synchronization isn't active
DEBUG [main]-fetching JDBC Connection from DataSource
Debu G [main]-JDBC Connection [Jdbc:mysql://localhost:3306/mybatis?characterencoding=utf-8, Username=root@localhost, Mysql-ab JDBC Driver] won't is managed by Spring
DEBUG [main]-==>  preparing:select * from USER WHERE id=? 
DEBUG [main]-==> parameters:1 (Integer)
debug [main]-<==      total:1
Debug [main]-Closing non transactional sqlsession [org.apache.ibatis.session.def Aults. DEFAULTSQLSESSION@13B5A3A]
DEBUG [main]-returning JDBC Connection to DataSource
1: Ms Cheung

Reprint please indicate the source: http://blog.csdn.net/acmman/article/details/46906717

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.