Spring+springmvc+mybatis Deep Learning and Building (ii)--mybatis original DAO development and Mapper Agent development (forwarding IBID.)

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:

Original address: http://www.cnblogs.com/shanheyongmu/p/7121016.html

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 interface Userdao {    //The user information is queried by ID    finduserbyid (int id) throws Exception;    Add user Information public    void Insertuser (user user) throws Exception;    Delete User information public    void deleteuser (int id) throws Exception;}
2.3 DAO interface Implementation Class
public class Userdaoimpl implements userdao{//needs to be injected into the DAO implementation class Sqlsessionfactory//The constructor method is injected into private sqlsessionfacto    Ry Sqlsessionfactory;        Public Userdaoimpl (Sqlsessionfactory sqlsessionfactory) {super ();    This.sqlsessionfactory = sqlsessionfactory; } @Override public User Finduserbyid (int id) throws Exception {sqlsession Sqlsession=sqlsessionfactory.opens        Ession ();        User User=sqlsession.selectone ("Test.finduserbyid", id);        Release resources Sqlsession.close ();    return user; } @Override public void Insertuser (user user) throws Exception {sqlsession Sqlsession=sqlsessionfactory.open        Session ();        Sqlsession.insert ("Test.insertuser", user);        Commit Transaction Sqlsession.commit ();    Release resources Sqlsession.close (); } @Override public void deleteuser (int id) throws Exception {sqlsession sqlsession=sqlsessionfactory.openses        Sion ();        Sqlsession.delete ("Test.deleteuser", id);   Commit a transaction     Sqlsession.commit ();    Release resources Sqlsession.close (); }}
2.4 Test Code
public class Userdaoimpltest {    private sqlsessionfactory sqlsessionfactory;        @Before public    void SetUp () throws ioexception{        //Create sqlsessionfactory        //mybatis configuration file        String resource = "Sqlmapconfig.xml";        Get configuration file stream        InputStream inputstream=resources.getresourceasstream (Resource);        Create a session factory, pass in MyBatis profile information        sqlsessionfactory=new Sqlsessionfactorybuilder (). Build (InputStream);    }        @Test public    void Finduserbyidtest () throws exception{        Userdao userdao=new Userdaoimpl (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
Package Joanna.yan.mybatis.mapper;import java.util.list;import joanna.yan.mybatis.entity.user;/** * equivalent to DAO interface * @ Author Joanna.yan * */public interface Usermapper {    //query user information by ID public users    finduserbyid (int id) throws Exceptio n;    Query user public by name    list<user> finduserbyname (String name) throws Exception;    Add user Information public    void Insertuser (user user) throws Exception;    Delete User information public    void deleteuser (int id) throws Exception;}
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--  <mapper namespace= "Joanna.yan.mybatis.mapper.UserMapper" >    <select id= "Finduserbyid" parametertype= " Java.lang.Integer "resulttype=" Joanna.yan.mybatis.entity.User ">        select * from User where id=#{id}    </ select>    <select id= "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 class Usermappertest {private Sqlsessionfactory sqlsessionfactory; @Before public void SetUp () throws ioexception{//create sqlsessionfactory//mybatis configuration file String Resourc        E= "Sqlmapconfig.xml";        Get configuration file stream InputStream Inputstream=resources.getresourceasstream (Resource);    Create a session factory, pass in MyBatis profile information sqlsessionfactory=new Sqlsessionfactorybuilder (). Build (InputStream); } @Test public void Finduserbyidtest () throws exception{sqlsession sqlsession=sqlsessionfactory.opensess        Ion ();        Create Usermapper object, MyBatis automatically generate Mapper proxy object Usermapper usermapper=sqlsession.getmapper (Usermapper.class);        Method of calling Usermapper User User=usermapper.finduserbyid (1);    SYSTEM.OUT.PRINTLN (user); } @Test public void Finduserbynametest () throws exception{sqlsession Sqlsession=sqlsessionfactory.opense        Ssion (); Create Usermapper object, MyBatis automatically generate Mapper proxy object Usermapper Usermapper=sqlsession.getmappER (usermapper.class);        Call Usermapper method list<user> List=usermapper.finduserbyname ("xiaoming");    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 (forwarding IBID.)

Related Article

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.