MyBatis Implement Mapper Dynamic proxy method

Source: Internet
Author: User
First, the realization principle


The Mapper interface development method requires only programmers to write mapper interfaces (equivalent to the DAO Interface), and the MyBatis framework creates interface dynamic proxy objects based on interface definitions, and the proxy object's method body implements the class method with the top DAO interface.




Mapper interface development needs to follow the following specifications:
1, the namespace in the Mapper.xml file is the same as the classpath of the Mapper interface.
2. The Mapper interface method name is the same as the ID of each statement defined in Mapper.xml
3, the input parameter type of the Mapper interface method is the same type as the parametertype of each SQL defined in Mapper.xml
4. The output parameter type of the Mapper interface method is the same type as the resulttype of each SQL defined in Mapper.xml 

Second, mapper.xml mapping file



To define the mapper mapping file Usermapper.xml (content Users.xml), you need to modify the namespace value to the Usermapper interface path. Place the Usermapper.xml under the Classpath Mapper directory.






<? 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.itcast.mybatis.mapper.UserMapper">
<!-Get user information based on id->
<select id = "findUserById" parameterType = "int" resultType = "cn.itcast.mybatis.po.User">
select * from user where id = # (id)
</ select>
<!-Custom criteria query user list->
<select id = "findUserByUsername" parameterType = "java.lang.String"
resultType = "cn.itcast.mybatis.po.User">
select * from user where username like '% $ (value}%'
</ select>
<!-Add user->
<insert id = "insertUser" parameterType = "cn.itcast.mybatis.po.User">
<selectKey keyProperty = "id" order = "AFTER" resultType = "java.lang.Integer">
select LAST_INSERT_ID ()
</ selectKey>
insert into user (username, birthday, sex, address)
values (# {username}, # {birthday}, # {sex}, # {address})
</ insert>

</ mapper> 

Third, Mapper.java (interface file)








/**
 * User Management Mapper/public
interface Usermapper {
	//query user information by User ID Public user
	finduserbyid (int id) Throws Exception;
	Query user list public
	list<user> Finduserbyusername (String username) throws Exception;
	Add user Information public
	void Insertuser (user user) throws Exception; 
}

Interface definitions have the following characteristics:
1, the Mapper interface method name and the Mapper.xml defined in the statement ID is the same
2, the input parameter type of the Mapper interface method is the same type as the parametertype of statement defined in Mapper.xml

3, the output parameter type of the Mapper interface method is the same type as the resulttype of statement defined in Mapper.xml 


Fourth. loading usermapper.xml files

To modify the Sqlmapconfig.xml file:






<!--load mapping file-->
  <mappers>
    <mapper resource= "Mapper/usermapper.xml"/>
  </mappers >

Fifth, Test







public class Usermappertest extends TestCase {private sqlsessionfactory sqlsessionfactory;
		protected void SetUp () throws Exception {//mybatis configuration file String resource = "Sqlmapconfig.xml";
		InputStream InputStream = resources.getresourceasstream (Resource); Use Sqlsessionfactorybuilder to create sessionfactory sqlsessionfactory = new Sqlsessionfactorybuilder (). Build (InputStream)
	; public void Testfinduserbyid () throws Exception {//get session sqlsession session = Sqlsessionfactory.opensession
		();
		Gets the proxy object of the Mapper interface Usermapper usermapper = Session.getmapper (Usermapper.class);
		Invoke proxy object method User user = Usermapper.finduserbyid (1);
		SYSTEM.OUT.PRINTLN (user);
		
	Closes session session.close (); @Test public void Testfinduserbyusername () throws Exception {sqlsession sqlsession = sqlsessionfactory.opensession (
		);
		Usermapper usermapper = Sqlsession.getmapper (Usermapper.class);
		list<user> list = Usermapper.finduserbyusername ("Zhang"); System.out.println (List.size ());
		public void Testinsertuser () throws Exception {//get session Sqlsession session = Sqlsessionfactory.opensession ();
		Gets the proxy object of the Mapper interface Usermapper usermapper = Session.getmapper (Usermapper.class);
		The data to be added user user = new user ();
		User.setusername ("John");
		User.setbirthday (New Date ());
		User.setsex ("1");
		User.setaddress ("Beijing");
		Add user Usermapper.insertuser through the Mapper interface;
		Submit Session.commit ();
	Closes session session.close ();
 }
	

}

Sixth. Summary





SelectOne and SelectList
Dynamic proxy object invocation Sqlsession.selectone () and sqlsession.selectlist () are determined based on the return value of the Mapper interface method, and the SelectList method is called if the list is returned. If a single object is returned, the SelectOne method is invoked.




Namespace
MyBatis official recommended the use of Mapper proxy method to develop the Mapper interface, programmers do not have to write Mapper interface implementation classes, the use of Mapper proxy method, input parameters can be used Pojo packaging objects or map objects, to ensure that DAO's versatility.


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.