Use of MyBatis (Mapper interface mode)

Source: Internet
Author: User

Using the Mapper interface, without writing the interface implementation class, directly complete the database operation, simple and convenient. In order to help everyone to better learn Mapper interface, small series summed up some knowledge about the Mapper interface, hope to help people in need.

First on the structure chart:

Here is the specific code:
First, User.java

The Get/set method in the entity class and the method of construction and the ToString method are not affixed with the public class User {        private int id;        private String name;        private int age;}

Second, Usermapper.java
This is the mapper interface, the idea of interface-oriented programming is still very important. is also the most important part of this blog post.

The interface definition has the following characteristics:

    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 parametertype type of SQL defined in Usermapper.xml.

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

Note the method for creating the table, annotated @param

Package Com.mi.mapper;import Org.apache.ibatis.annotations.param;import Com.mi.beans.user;public interface usermapper {    void CreateTable (@Param ("TableName") String tableName);    void Add (user user);    void del (int id);    void update (user user);    User getUser (int id);    User[] List ();}

Third, Usermappers.xml
we need to be aware
The namespace of the 1.xml file is written as the path to the Mapper interface, as shown below.

<mapper namespace= "Com.mi.mapper.UserMapper" >

2. When writing statements that dynamically create tables, write ${tablename} instead of #{}. Click to see the difference between the two

CREATE TABLE ${tablename} ...

Here's the full code: including creating tables, CRUD

<?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" ><!-- Specifying a unique Namespace,namespace value for this mapper is customarily set to the package name +sql the map file name so that the namespace value is guaranteed to be unique--><mapper namespace= " Com.mi.mapper.UserMapper "> <!--CREATE table-<update id=" createtable "parametertype=" String "> creat e table ${tablename} (ID int primary key auto_increment,name varchar (), age int) </update> <!--add Data--&gt    ; <insert id= "Add" parametertype= "Com.mi.beans.User" > INSERT into T_user (name,age) value (#{name},#{age}) &lt ;/insert> <!--Delete data-<delete id= "del" parametertype= "int" > delete from t_user where id = #{ ID} </delete> <!--modify Data-<update id= "Update" parametertype= "Com.mi.beans.User" > Updat E t_user set Name=#{name},age=#{age} where Id=#{id} </update> <!--to get a user object based on ID--<seLect id= "GetUser" parametertype= "int" resulttype= "Com.mi.beans.User" > select * from T_user where id=#{id } </select> <!--query All users--<select id= "list" resulttype= "Com.mi.beans.User" > select *           From T_user; </select></mapper>

Iv. Conf.xml
There are two things to configure here.

    • Configuring a JDBC Connection

    • Configure Mapper.xml

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" >            <configuration> <environments default= "Development" > <environment id= "Development" >                <transactionmanager type= "JDBC"/> <!--Configuring database connection Information--<datasource type= "Pooled" > <property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value                = "Jdbc:mysql://localhost:3306/mybatis"/> <property name= "username" value= "root"/> <property name= "Password" value= "root"/> </dataSource> </environment> </enviro nments> <!--register Usermapper.xml file--<mappers> <mapper resource= "Com/mi/mapping/usermapp Ers.xml "/> </mappers></configuration> 

Wu, Sqlsessionutil.java
I wrote a tool class here, the main purpose is to get sqlsession, because after each operation of the database will need to write again, so a package.

Package Com.mi.util;import Java.io.inputstream;import Org.apache.ibatis.io.resources;import Org.apache.ibatis.session.sqlsession;import Org.apache.ibatis.session.sqlsessionfactory;import Org.apache.ibatis.session.sqlsessionfactorybuilder;public class Sqlsessionutil {public      static sqlsession Getsqlsession () throws exception{      String resource = "Conf.xml";      Use the class loader to load the MyBatis configuration file (It also loads the associated mapping file)      InputStream is = resources.getresourceasstream (Resource);      Build sqlsession Factory      sqlsessionfactory sessionfactory = new Sqlsessionfactorybuilder (). Build (IS);      Create sqlsession      sqlsession sqlsession = sessionfactory.opensession () that can execute SQL in the mapping file;      return sqlsession;}   }

Liu, Mytest.java
This is the test class, through the above tool class sqlsession, the most critical is the following sentence

Usermapper usermapper = Sqlsession.getmapper (Usermapper.class);

MyBatis through the dynamic proxy way to implement the Mapper interface , after the good run, the implementation of the interface in the prepared method is ok.
Be careful not to forget Sqlsession.commit () and Sqlsession.close (). Otherwise, there will be no error during execution, but there is no change in the database.

Here I only performed the method of creating the table. Package Com.mi.test;import Org.apache.ibatis.session.sqlsession;import Com.mi.beans.user;import Com.mi.mapper.usermapper;import Com.mi.util.sqlsessionutil;public class MyTest {public    static void Main (string[] args) throws Exception {        sqlsession sqlsession = sqlsessionutil.getsqlsession ();        Usermapper usermapper = Sqlsession.getmapper (usermapper.class);        Usermapper.createtable ("T_user");        Sqlsession.commit ();        Sqlsession.close ();    }}

Using the Mapper interface, without writing the interface implementation class, directly complete the database operation, simple and convenient.
First on the structure chart:

Here is the specific code:
First, User.java

The Get/set method in the entity class and the method of construction and the ToString method are not affixed with the public class User {    private int id;    private String name;    private int age;

Second, Usermapper.java
This is the mapper interface, the idea of interface-oriented programming is still very important. is also the most important part of this blog post.

The interface definition has the following characteristics:

    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 parametertype type of SQL defined in Usermapper.xml.

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

Note the method for creating the table, annotated @param

Package Com.mi.mapper;import Org.apache.ibatis.annotations.param;import Com.mi.beans.user;public interface usermapper {    void CreateTable (@Param ("TableName") String tableName);    void Add (user user);    void del (int id);    void update (user user);    User getUser (int id);    User[] List ();}

Third, Usermappers.xml
we need to be aware
The namespace of the 1.xml file is written as the path to the Mapper interface, as shown below.

<mapper namespace= "Com.mi.mapper.UserMapper" >

2. When writing statements that dynamically create tables, write ${tablename} instead of #{}. Click to see the difference between the two

CREATE TABLE ${tablename} ...

Here's the full code: including creating tables, CRUD

<?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" ><!-- Specifying a unique Namespace,namespace value for this mapper is customarily set to the package name +sql the map file name so that the namespace value is guaranteed to be unique--><mapper namespace= " Com.mi.mapper.UserMapper "> <!--CREATE table-<update id=" createtable "parametertype=" String "> creat e table ${tablename} (ID int primary key auto_increment,name varchar (), age int) </update> <!--add Data- -<insert id= "Add" parametertype= "Com.mi.beans.User" > INSERT into T_user (name,age) value (#{name},#{age }) </insert> <!--delete data--<delete id= "del" parametertype= "int" > Delete from T_user WHERE id = #{id} </delete> <!--modify Data-<update id= "Update" parametertype= "Com.mi.beans.User"        ; Update T_user set Name=#{name},age=#{age} where Id=#{id} </update> <!--to get a user object based on the ID query--> <select id= "getUser" parametertype= "int" resulttype= "Com.mi.beans.User" > select * from T_user where Id=#{id} </select> <!--query All users--<select id= "list" resulttype= "Com.mi.beans.User"        ;           SELECT * from T_user; </select></mapper>

Iv. Conf.xml
There are two things to configure here.

    • Configuring a JDBC Connection

    • Configure Mapper.xml

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" >            <configuration> <environments default= "Development" > <environment id= "Development" >                <transactionmanager type= "JDBC"/> <!--Configuring database connection Information--<datasource type= "Pooled" > <property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value                = "Jdbc:mysql://localhost:3306/mybatis"/> <property name= "username" value= "root"/> <property name= "Password" value= "root"/> </dataSource> </environment> </enviro nments> <!--register Usermapper.xml file--<mappers> <mapper resource= "Com/mi/mapping/use Rmappers.xml "/> </mappers></configuration>

Wu, Sqlsessionutil.java
I wrote a tool class here, the main purpose is to get sqlsession, because after each operation of the database will need to write again, so a package.

Package Com.mi.util;import Java.io.inputstream;import Org.apache.ibatis.io.resources;import Org.apache.ibatis.session.sqlsession;import Org.apache.ibatis.session.sqlsessionfactory;import Org.apache.ibatis.session.sqlsessionfactorybuilder;public class Sqlsessionutil {public      static sqlsession Getsqlsession () throws exception{        String resource = "Conf.xml";         Use the class loader to load the MyBatis configuration file (It also loads the associated mapping file)        InputStream is = resources.getresourceasstream (Resource);        Build sqlsession Factory        sqlsessionfactory sessionfactory = new Sqlsessionfactorybuilder (). Build (IS);      Create sqlsession        sqlsession sqlsession = sessionfactory.opensession () that can execute SQL in the mapping file;        return sqlsession;}    }

Liu, Mytest.java
This is the test class, through the above tool class sqlsession, the most critical is the following sentence

Usermapper usermapper = Sqlsession.getmapper (Usermapper.class);

MyBatis through the dynamic proxy way to implement the Mapper interface , after the good run, the implementation of the interface in the prepared method is ok.
Be careful not to forget Sqlsession.commit () and Sqlsession.close (). Otherwise, there will be no error during execution, but there is no change in the database.

Here I only performed the method of creating the table. Package Com.mi.test;import Org.apache.ibatis.session.sqlsession;import Com.mi.beans.user;import Com.mi.mapper.usermapper;import Com.mi.util.sqlsessionutil;public class MyTest {public    static void Main (string[] args) throws Exception {        sqlsession sqlsession = sqlsessionutil.getsqlsession ();        Usermapper usermapper = Sqlsession.getmapper (usermapper.class);        Usermapper.createtable ("T_user");        Sqlsession.commit ();        Sqlsession.close ();    }}

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.