MyBatis the method of developing DAO usually uses two kinds, one is the traditional DAO method, one is based on the Mapper proxy method, the following study these two kinds of development pattern.
You should have a more detailed understanding of sqlsession before writing DAO.
I. Scope of use of MyBatis sqlsession
Sqlsessionfactorybuilder is used to create sqlsessionfacoty,sqlsessionfacoty once created, no sqlsessionfactorybuilder is needed. Because Sqlsession is produced by Sqlsessionfactory, Sqlsessionfactorybuilder can be used as a tool class, and the best use range is the method scope, the method body local variables.
Sqlsessionfactory is an interface that defines the different overloaded methods of opensession, the best use of sqlsessionfactory is the entire application run, once created can be reused, Sqlsessionfactory is usually managed in a singleton mode.
- The operation of the database is encapsulated in sqlsession, such as querying, inserting, updating, deleting, and so on. Sqlsession is created through sqlsessionfactory , and Sqlsessionfactory is created through sqlsessionfactorybuilder .
- Sqlsession is a user-oriented interface that defines database operations in Sqlsession and uses Defaultsqlsession implementation classes by default.
The specific implementation process is as follows:
- Loading configuration information such as data sources environment environment = configuration.getenvironment ();
- Create a database link
- Create transaction object creation Executor,sqlsession All operations are done through executor
Corresponding Source:
if (ExecutorType.BATCH == executorType) { executor = newBatchExecutor(this, transaction); } elseif (ExecutorType.REUSE == executorType) { new ReuseExecutor(this, transaction); else { new SimpleExecutor(this, transaction); }if (cacheEnabled) { new CachingExecutor(executor, autoCommit); }
Conclusion it is concluded
Each thread should have its own sqlsession instance. An instance of sqlsession cannot be shared, and it is also thread insecure. The best range is therefore the request or method scope. You must never place a reference to a sqlsession instance in a static field or instance field of a class.
Open a sqlsession, and close it when you're finished. This close operation is usually placed in a finally block to ensure that the shutdown can be performed every time.
Two. Traditional DAO development method
The traditional approach is to establish a DAO interface definition method and then create its implementation class to implement the methods in DAO. The following code is the first example.
Regardless of the development method, Mapper.xml is written, the mapper mapping also needs to be configured in Sqlmapperconfig.xml
1.user.xml Writing
The same as in the previous article, here for the complete process to post it.
<?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" ;<!--namespaces for isolating SQL statements, which later speak the very important role of another layer. -<mapper namespace="Test"> <!--Query the user information by ID (query one piece of data)-- <select id="Finduserbyid" parametertype="int" resulttype ="Com.aust.model.User">SELECT * from user WHERE Id=#{id}</Select> <!--fuzzy query by name (more than one data query)-- <select id="Finduserbyname" parametertype=" Java.lang.String " resulttype=" Com.aust.model.User ">SELECT * from user WHERE nickname like '%${value}% '</Select> <!--inserting a user -- <insert id="Insertuser" parametertype="Com.aust.model.User" > <selectkey keyproperty= "id" resulttype=" Java.lang.Integer " order=" after " >SELECT last_insert_id ()</selectkey>INSERT into User (Username,password,nickname,status) VALUE (#{username},#{password},#{nickname},#{status})</Insert> <!--Delete a user -- <delete id="DeleteUser" parametertype="int">DELETE from user WHERE ID =#{id}</Delete> <!--update users -- <update id="UpdateUser" parametertype="Com.aust.model.User" >UPDATE user SET Username=#{username},password=#{password},nickname=#{nickname} WHERE id = #{id}</Update></mapper>
2. Configuring Mapper Mappings
Configure in Sqlmapperconfig,xml
<!--配置mappeer映射--> <mappers> <mapper resource="mapper/User.xml"/> </mappers>
3. Implementing the DAO Interface
Public interface Userdao { //query users by ID PublicUserFinduserbyid(intID);//Fuzzy query for users by name PublicList<user>Finduserbyname(String name);//Insert a user, return primary key Public int Insertuser(user user);//Delete a user Public Boolean DeleteUser(intID);//Update a user Public Boolean UpdateUser(user user);}
4. Implementing the DAO Interface implementation class
Public class userdaoimp implements Userdao{ PrivateSqlsessionfactory Factory;//through the construction of injection sqlsessionfactory, the late integration of spring, all to spring management Public Userdaoimp(Sqlsessionfactory Factory) { This. factory = Factory; }@Override PublicUserFinduserbyid(intID) {//Put in the method body to create, ensure thread safetysqlsession session = Factory.opensession (); User user = Session.selectone ("Test.finduserbyid", id); Session.close ();returnUser }@Override PublicList<user>Finduserbyname(String name) {//Put in the method body to create, ensure thread safetysqlsession session = Factory.opensession (); list<user> users = session.selectlist ("Test.finduserbyname", name); Session.close ();returnUsers }@Override Public int Insertuser(User user) {//Put in the method body to create, ensure thread safetysqlsession session = Factory.opensession (); Session.insert ("Test.insertuser", user);//must be submitted, otherwise it is a failureSession.commit (); Session.close ();returnUser.getid (); }@Override Public Boolean DeleteUser(intID) {//Put in the method body to create, ensure thread safetysqlsession session = Factory.opensession ();inti = Session.delete ("Test.deleteuser", id);//must be submitted, otherwise it is a failureSession.commit (); Session.close ();returnI>0; }@Override Public Boolean UpdateUser(User user) {//Put in the method body to create, ensure thread safetysqlsession session = Factory.opensession ();inti = Session.delete ("Test.updateuser", user);//must be submitted, otherwise it is a failureSession.commit (); Session.close ();returnI>0; }}
5. Write JUnit Tests
Sqlsessionfactory factory =NULL; @Before Public void Init() {InputStream is=NULL;Try{ is= Resources.getresourceasstream ("Sqlmapperconfig.xml"); }Catch(IOException e) {E.printstacktrace (); } factory =NewSqlsessionfactorybuilder (). Build ( is); }//test take out a single@Test Public void finduserbyidtest() {Userdaoimp Daoimp =NewUserdaoimp (Factory); User user = Daoimp.finduserbyid (2); System. out. println (user); }//test Remove multiple@Test Public void finduserbynametest() {Userdaoimp Daoimp =NewUserdaoimp (Factory); list<user> users = Daoimp.finduserbyname ("Zhang"); System. out. println (users); }//Test Insert Data@Test Public void insertusertest() {Userdaoimp Daoimp =NewUserdaoimp (Factory); User U =NewUser (); U.setusername ("Niuli1"); U.setpassword ("123456"); U.setnickname ("Niu Li"); U.setstatus (2);intindex = Daoimp.insertuser (u); System. out. println (index); }
The above five steps is the traditional DAO development method
6. Problems existing in the original DAO development method
- Duplicate code exists in DAO method body: Create sqlsession through Sqlsessionfactory, call Sqlsession's database operation method
- The database operation method called Sqlsession needs to specify the ID of the statement, which is hard coded and not for development maintenance.
Two. Based on the Mapper Agent interface 1. Principle of implementation
Mapper interface development method only requires programmers to write the Mapper interface (equivalent to DAO interface), the MyBatis framework creates an interface based on the interface definition of the dynamic proxy object, the proxy object's method body with the upper DAO interface implementation class method. In other words, the implementation class of the DAO interface is not written by the programmer itself.
2.UserMapper interface
The interface definition has the following characteristics:
1. The ID of the Mapper interface method name and the statement defined in the Mapper.xml are the same
2. The input parameter type of the Mapper interface method is the same as the ParameterType type of the statement defined in the Mapper.xml
3. The output parameter type of the Mapper interface method is the same as the Resulttype type of the statement defined in the Mapper.xml
Public InterfaceUsermapper {//query users by ID PublicUserFinduserbyid(intID);//Fuzzy query for users by name PublicList<user>Finduserbyname(String name);//Insert a user, return the number of rows affected Public int Insertuser(user user);//Delete a user, return the number of rows affected Public int DeleteUser(intID);//Update one user, return the number of rows affected Public int UpdateUser(user user);}
3.usermapper.xml
Mapper interface development is subject to the following specifications:
1. The namespace in the Mapper.xml file is the same as the classpath of the Mapper interface.
<?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代理的话要是Mapper代理类路径。--><mapper namespace="com.aust.dao.UserMapper"> <!--其余内容和上面的User.xml一样--></mapper>
4. Configuring Mapper Mappings
Either way, you need to configure the mapping
<!--配置mappeer映射--> <mappers> <mapper resource="mapper/UserMapper.xml"/> </mappers>
5. Write JUnit Tests
@Before Public void Init() {InputStream is=NULL;Try{ is= Resources.getresourceasstream ("Sqlmapperconfig.xml"); }Catch(IOException e) {E.printstacktrace (); } factory =NewSqlsessionfactorybuilder (). Build ( is); }//test take out a single@Test Public void finduserbyidtest(){//Get sqlsessionsqlsession session = Factory.opensession ();//Create mapper AgentUsermapper mapper = Session.getmapper (Usermapper.class);//Using mapper proxy queryUser u = Mapper.finduserbyid (2); Session.close (); System. out. println (U); }//test Remove multiple@Test Public void finduserbynametest() {sqlsession session = Factory.opensession (); Usermapper mapper = Session.getmapper (Usermapper.class); list<user> users = Mapper.finduserbyname ("Zhang"); Session.close (); System. out. println (users); }//Test Insert Data@Test Public void insertusertest() {sqlsession session = Factory.opensession (); Usermapper mapper = Session.getmapper (Usermapper.class); User U =NewUser (); U.setusername ("Niuli1"); U.setpassword ("123456"); U.setnickname ("Niu Li"); U.setstatus (2);intindex = Mapper.insertuser (u); System. out. println (index);//Gets the number of rows affectedSystem. out. println (U.getid ());//Get returned self-increment primary key}
6. Summary
- The SelectOne and SelectList dynamic proxy object calls Sqlsession.selectone () and sqlsession.selectlist () are determined based on the return value of the Mapper interface method. If a list is returned, the SelectList method is called, and if a single object is returned, the SelectOne method is called.
- MyBatis officially recommends using the Mapper proxy method to develop mapper interfaces, and programmers do not have to write Mapper interface implementation classes .
- You can find the way to use the Mapper proxy, the input parameters in the Mapper interface must be only one, but how can you satisfy a variety of queries? MyBatis recommended input parameters can use Pojo wrapper object or Map object to ensure the universality of DAO.
MyBatis Learning Record (ii)--mybatis developing DAO Way