Spring+springmvc+mybatis Deep Learning and Building (ii)--mybatis original DAO development and Mapper agent development

Source: Internet
Author: User

There is a basic knowledge of spring+springmvc+mybatis in-depth learning and building (a)--mybatis. There is a lot of duplicated code in Mybatisfirst. This simplifies the code:

Using MyBatis to develop DAO, there are usually two methods, the original DAO development method and the Mapper interface development method.

1.SqlSession Range of Use

1.1 Sqlsessionfactorybuilder

Create session Factory Sqlsessionfactory with Sqlsessionfactorybuilder, use Sqlsessionfactorybuilder as a tool class, You do not need to use a singleton management sqlsessionfactorybuilder.

When you need to create sqlsessionfactory, you only need to sqlsessionfactorybuilder new once.

1.2 Sqlsessionfactory

Create sqlsession with sqlsessionfactory, use singleton mode to manage Sqlsessionfactory (once the factory is created, use one instance).

Once MyBatis and spring are integrated, use Singleton mode to manage Sqlsessionfactory.

1.3 sqlsession

Sqlsession is a user-oriented (programmer) interface.

Sqlsession provides a number of ways to manipulate the database, such as SelectOne (returning a single object), SelectList (returning single or multiple objects).

Sqlsession is thread insecure, and in the Sqlsession implementation class there are data field properties in addition to the methods in the interface (the method that operates the database).

Sqlsession the best application in the method body, defined as local variable use.

2. Original DAO development method (Programmer needs to write DAO interface and DAO implementation Class) 2.1 Ideas

Programmers need to write DAO interfaces and DAO implementation classes.

You need to inject sqlsessionfactory into the DAO's implementation class to create sqlsession through Sqlsessionfactory in the method body.

2.2 DAO Interface
 Public InterfaceUserdao {//query user information by ID     PublicUser Finduserbyid (intIdthrowsException; //Add user Information     Public voidInsertuser (user user)throwsException; //Delete User Information     Public voidDeleteUser (intIdthrowsException;}
2.3 DAO interface Implementation Class
 Public classUserdaoimplImplementsuserdao{//need to inject sqlsessionfactory into the DAO implementation class//this is injected through the construction method    Privatesqlsessionfactory sqlsessionfactory;  PublicUserdaoimpl (sqlsessionfactory sqlsessionfactory) {Super();  This. Sqlsessionfactory =sqlsessionfactory; } @Override PublicUser Finduserbyid (intIdthrowsException {sqlsession sqlsession=sqlsessionfactory.opensession (); User User=sqlsession.selectone ("Test.finduserbyid", id); //Freeing ResourcesSqlsession.close (); returnuser; } @Override Public voidInsertuser (user user)throwsException {sqlsession sqlsession=sqlsessionfactory.opensession (); Sqlsession.insert ("Test.insertuser", user); //Commit a transactionSqlsession.commit (); //Freeing ResourcesSqlsession.close (); } @Override Public voidDeleteUser (intIdthrowsException {sqlsession sqlsession=sqlsessionfactory.opensession (); Sqlsession.delete ("Test.deleteuser", id); //Commit a transactionSqlsession.commit (); //Freeing ResourcesSqlsession.close (); }}
2.4 Test Code
 Public classUserdaoimpltest {Privatesqlsessionfactory sqlsessionfactory; @Before Public voidSetUp ()throwsioexception{//Create Sqlsessionfactory//mybatis configuration fileString resource= "Sqlmapconfig.xml"; //get configuration file streamInputStream inputstream=Resources.getresourceasstream (Resource); //creating a session factory, passing in MyBatis profile informationsqlsessionfactory=NewSqlsessionfactorybuilder (). Build (InputStream); } @Test Public voidFinduserbyidtest ()throwsexception{Userdao Userdao=NewUserdaoimpl (sqlsessionfactory); User User=userdao.finduserbyid (1);    SYSTEM.OUT.PRINTLN (user); }}
2.5 summarizing the original DAO development problem

(1) There are a lot of template methods in the DAO interface implementation class method, it is envisaged that the code can be extracted and greatly reduce the workload of the programmer.

(2) The ID of the statement is hard-coded when calling the Sqlsession method.

(3) The variable passed in when calling the Sqlsession method, because the Sqlsession method uses generics, even if the variable type passed in the error, in the compilation stage also does not error, is not conducive to programmer development.

3.mapper Proxy Method (programmer only need to write Mapper interface (equivalent to DAO interface)) 3.1 Ideas (mapper Agent development Code)

Programmers need to write mapper.xml mapping files

Programmers writing mapper interfaces need to follow some development specifications, MyBatis can automatically generate Mapper interface implementation class proxy objects.

Development specification:

(1) Namespace equals Mapper interface address in Mapper.xml

(2) The method name in the Mapper.java interface is consistent with the statement ID in the Mapper.xml

(3) The method input parameter type in the Mapper.java interface is consistent with the type of parametertype specified in mapper.xml statement.

(4) The method return value type in the Mapper.java interface is the same as the resulttype specified in mapper.xml statement.

Summarize:

The above method development specification mainly is the following code to unify the generation:

User user = Sqlsession.selectone ("Test.finduserbyid", id), Sqlsession.insert ("Test.insertuser", user); ......
3.2 Mapper.java
 PackageJoanna.yan.mybatis.mapper;Importjava.util.List;ImportJoanna.yan.mybatis.entity.User;/*** equivalent to DAO interface *@authorJoanna.yan **/ Public InterfaceUsermapper {//query user information by ID     PublicUser Finduserbyid (intIdthrowsException; //query users by name     PublicList<user> finduserbyname (String name)throwsException; //Add user Information     Public voidInsertuser (user user)throwsException; //Delete User Information     Public voidDeleteUser (intIdthrowsException;}
3.3 Mapper.xml
<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE mapperpublic "-//mybatis.org//dtd Mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd "><!--namespace namespace, the role is to classify the SQL management, understood as SQL Isolation Note: When using Mapper agent development, namespace has a special role, namespace equals the Mapper interface address -<Mappernamespace= "Joanna.yan.mybatis.mapper.UserMapper">    <SelectID= "Finduserbyid"ParameterType= "Java.lang.Integer"Resulttype= "Joanna.yan.mybatis.entity.User">SELECT * from user where Id=#{id}</Select>    <SelectID= "Finduserbyname"ParameterType= "Java.lang.String"Resulttype= "Joanna.yan.mybatis.entity.User">SELECT * from user where username like '%${value}% '</Select></Mapper>
3.4 Loading Mapper.xml in Sqlmapconfig.xml

3.5 Testing
 Public classUsermappertest {Privatesqlsessionfactory sqlsessionfactory; @Before Public voidSetUp ()throwsioexception{//Create Sqlsessionfactory//mybatis configuration fileString resource= "Sqlmapconfig.xml"; //get configuration file streamInputStream inputstream=Resources.getresourceasstream (Resource); //creating a session factory, passing in MyBatis profile informationsqlsessionfactory=NewSqlsessionfactorybuilder (). Build (InputStream); } @Test Public voidFinduserbyidtest ()throwsexception{sqlsession sqlsession=sqlsessionfactory.opensession (); //Create Usermapper object, MyBatis automatically generate Mapper proxy objectUsermapper Usermapper=sqlsession.getmapper (Usermapper.class); //methods for calling UsermapperUser User=usermapper.finduserbyid (1);    SYSTEM.OUT.PRINTLN (user); } @Test Public voidFinduserbynametest ()throwsexception{sqlsession sqlsession=sqlsessionfactory.opensession (); //Create Usermapper object, MyBatis automatically generate Mapper proxy objectUsermapper Usermapper=sqlsession.getmapper (Usermapper.class); //methods for calling UsermapperList<user> list=usermapper.finduserbyname ("Xiao Ming");    SYSTEM.OUT.PRINTLN (list); }}
3.6 Some issues summary 3.6.1 proxy object Internal call SelectOne or SelectList

If the Mapper method returns a single Pojo object (not a collection object), the proxy object queries the database internally through SelectOne.

If the Mapper method returns a collection object, the proxy object internally queries the database through SelectList.

3.6.2 Mapper Interface method parameters can only have one effect on system development

Mapper interface method parameters can only have one, whether the system is not conducive to extended maintenance.

In the system framework, the DAO layer code is common to the business layer.

Even if the Mapper interface has only one parameter, the Pojo of the wrapper type can be used to meet the needs of different business methods.

Note: The parameters of the persistence layer method can be wrapped type, map, and so on, the service method is not recommended to use the wrapper type (not conducive to the scalability of the business layer).

Spring+springmvc+mybatis Deep Learning and Building (ii)--mybatis original DAO development and Mapper agent development

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.