Use of MyBatis II (use of Mapper interface)

Source: Internet
Author: User

First, in the previous article, there are some problems:

1. No interface programming is used, and Java is an interface-oriented programming language. You should define some interfaces for database operations and invoke the DAO interface to complete database operations.

public interface userdao {//query user information by ID Public user finduserbyid (int userId)   throws exception;//Add User Public void insertuser (User user)  throws exception;// Modify User Public void updateuser (user user)  throws exception;//Delete user public void  DeleteUser (Int userid)  throws exception;} public class userdaoimpl implements userdao {private sqlsessionfactory  sqlsessionfactory;// SqlSessionFactory  injection through spring, there is no spring, temporarily using the construction method instead of public void  Setsqlsessionfactory (sqlsessionfactory sqlsessionfactory)  {this.sqlSessionFactory =  Sqlsessionfactory;} Public userdaoimpl (sqlsessionfactory sqlsessionfactory)  {this.setsqlsessionfactory ( Sqlsessionfactory);} @Overridepublic  user finduserbyid (Int userid)  throws Exception {SqlSession  sqlsession = null; User user = null; try {//obtains sqlsessionsqlsession = sqlsessionfactory.opensession through sqlsessionfactory;// Use session to manipulate the database//selectone the first parameter: Specify the ID of the SQL (STATEMENT ID), pay attention to namespace, and the second argument: the parameter values passed to SQL user =  Sqlsession.selectone ("Test.finduserbyid",  userid); SYSTEM.OUT.PRINTLN (user);}  catch  (exception e)  {// todo: handle exception} finally {if   (Sqlsession != null)  {sqlsession.close ();}} Return user;} @Overridepublic  void insertuser (User user)  throws Exception {SqlSession  sqlsession = null;try {//get sqlsessionsqlsession =  through Sqlsessionfactory Sqlsessionfactory.opensession ();//Use Session Operation Database Sqlsession.insert ("Test.insertuser",  user);// Commit Transaction Sqlsession.commit ();}  catch  (exception e)  {// todo: handle exception} finally {if   (Sqlsession != null)  {sqlsession.close ();}}}

2. Although the above is a way of implementing a DAO interface implementation class, it is necessary to call Sqlsession's SelectOne () method when accessing SQL defined in the SQL mapping file, and pass the location of SQL (namespace + ID) and parameters to SelectOne ( ) method, and the first argument is a long string, the second argument is an object, and an error in writing the code cannot be found during the compilation phase.

Optimization:

The first step: Define the Usermapper.xml, also use the original without changing

Step two: Define the Mapper interface

Public interface Usermapper {//query user information based on ID-public user finduserbyid (int userId) throws exception;//add user public void Insertuser (user user) throws exception;//Modify user public void Updateuserbyid (user user) throws exception;//Delete user public void Deleteuserbyid (int userId) throws Exception;}

The interface definition has the following characteristics:

A. The Mapper interface method name and the ID of each SQL defined in usermapper. XML have the same name.

B. The input parameter type of the Mapper interface method is the same as the SQL ParameterType type defined in usermapper. Xml.

C. The output parameter type of the Mapper interface is the same as the Resulttype type of SQL defined in usermapper. Xml.

Step three: Modify the namespace of usermapper. xml

The modified namespace is the classpath of the Mapper interface.

<mapper namespace= "Mybatis.mapper.UserMapper" >

Fourth step: Call statement to operate the database via the Mapper interface

public class usermappertest extends testcase {private sqlsessionfactory  Sqlsessionfactory; string resource =  "Sqlmapconfig.xml";//method to be performed by any test method @overrideprotected void setup ()  throws exception {super.setup ();//Read configuration file via input stream inputstream inputstream =  Resources.getresourceasstream (Resource);//Get sqlsessionfactorysqlsessionfactory = new  Sqlsessionfactorybuilder (). Build (InputStream);} Public user testfinduserbyid ()  throws exception {//get sqlsessionsqlsession  Sqlsession = sqlsessionfactory.opensession ();//Specifies the type of  mapper  interface, MyBatis Implements Mapper Interface Usermapper usermapper = sqlsession.getmapper (Usermapper.class) through dynamic proxy; User user = usermapper.finduserbyid (100101); Sqlsession.commit (); Sqlsession.close ();// Query the user with primary key 100101 and output System.out.println ("User---"  + user); return user;} Public void testinsertuser ()  tHrows exception {sqlsession sqlsession = sqlsessionfactory.opensession ();//designation   The type of the mapper  interface, MyBatis implements the Mapper interface through dynamic proxy usermapper usermapper = sqlsession.getmapper ( Usermapper.class); User user = new user (); User.setusername ("Dina"); User.setsex ("0"); User.setbirthday (new  date ()); User.setaddress ("redwood city"); User.setdetail ("Good person"); User.setscore (99.2f); Usermapper.insertuser (user); Sqlsession.commit (); Sqlsession.close ();} Public void testupdateuserbyid ()  throws exception {sqlsession sqlsession =  sqlsessionfactory.opensession ();//Specifies the type of the  mapper  interface, MyBatis implements the Mapper interface by means of a dynamic proxy usermapper  Usermapper = sqlsession.getmapper (Usermapper.class); User user = new user (); User.setuserid (100102); User.setusername ("Golden"); User.setSex ("0"); User.setbirthday (New date ()); User.setaddress ("Shen zhen"); User.setdetail ("Good person")); User.setscore (89.2f); Usermapper.updateuserbyid (user); Sqlsession.commit (); Sqlsession.close ();} Public void testdeleteuserbyid ()  throws exception {sqlsession sqlsession =  sqlsessionfactory.opensession (); Usermapper usermapper = sqlsession.getmapper (Usermapper.class); UserMapper.deleteUserById (100110 ); Sqlsession.commit (); Sqlsession.close ();}}


Summarize:

Using the Mapper interface, without writing interface implementation class interface to complete the database operation, simple and convenient, this method is the official recommendation.

is a very important usage of mybatis.

Using the Mapper interface call must have the following conditions:

    1. The Mapper interface method name and the ID of each SQL defined in Usermapper.xml have the same name.

    2. The input parameter type of the Mapper interface method is the same as the SQL ParameterType type defined in Usermapper.xml.

    3. The output parameter type of the Mapper interface is the same as the Resulttype type of SQL defined in Usermapper.xml.

    4. The namespace in the Usermapper.xml file is the classpath of the Mapper interface.

Use of MyBatis II (use of Mapper interface)

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.