MyBatis using annotations on interfaces to configure SQL statements and interfaces to use with XML

Source: Internet
Author: User
Tags assert

Configuring SQL statements with annotations on an interface

MyBatis <select>,<update> provides a corresponding annotation-based configuration item for most XML-based mapper elements, including. In some cases, however, annotation-based configurations cannot support some XML-based elements. MyBatis provides a variety of annotations to support different types of statements (statement) such as Select,insert,update,delete. Let's briefly demonstrate how these basic annotations are used by a small demo:

I now have a student table with the following table structure:

First write the fields of the table encapsulation class, the code is as follows:

package org.zero01.pojo;public class Student {    private int sid;    private String sname;    private int age;    private String sex;    private String address;    ... getter setter 略 ...}

Then need to write an interface, the interface of the method to configure the annotations, the name of the annotations are basically self-explanatory, I do not repeat their role here. The code is as follows:

package org.zero01.mapper;import org.apache.ibatis.annotations.delete;import Org.apache.ibatis.annotations.insert;import Org.apache.ibatis.annotations.select;import Org.apache.ibatis.annotations.update;import Org.zero01.pojo.student;import Java.util.list;public Interface Studentmapper {@Insert ("Insert into student (sname,age,sex,address) VALUES (#{sname},#{age},#{sex},#{address})") Publ IC int insertstu (Student Student); @Delete ("Delete from student where sid=#{0}") public int delstu (int sid); @Select ("SELECT * from student where sid=#{0}") public student Selectbyid (int sid); @Select ("SELECT * FROM student") Public list<student> SelectAll (); @Select ("SELECT * FROM student limit #{param1},#{param2}") Public list<student> selectbylimit (int startrow, int e Ndrow); @Update ("Update student set Sname=#{sname},age=#{age},sex=#{sex},address=#{address} where Sid=#{sid}") public int UPDA Testu (Student Student);} 

The contents of the

MyBatis configuration file are as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.d TD "><configuration> <typeAliases> <typealias type=" org.zero01.pojo.Student "alias=" Student "/&G        T <typealias type= "Org.zero01.pojo.StudentLog" alias= "Studentlog"/> </typeAliases> <environments Defau            lt= "Development" > <environment id= "Development" > <transactionmanager type= "JDBC"/>                <datasource type= "Pooled" > <property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "Jdbc:mysql:///school"/> <property name= "username" value= "root" /> <property name= "password" value= "Your_password"/> </dataSource> </en Vironment> </environments> <mappers> <!--introduce interface via package name--> <mapper class= "Org.zero01.mapper.StudentMapper"/> </mappers></configuration>

Write a test class to test with the following code:

Package Org.zero01.test;import Org.apache.ibatis.io.resources;import Org.apache.ibatis.session.sqlsession;import Org.apache.ibatis.session.sqlsessionfactory;import Org.apache.ibatis.session.sqlsessionfactorybuilder;import Org.junit.after;import Org.junit.before;import Org.junit.test;import Org.zero01.student.student;import Java.io.ioexception;import Java.io.inputstream;import Java.util.list;public class Testmybatis {private SqlSession sql    Session;    Private Studentmapper Studentmapper; Load resource @Before public void Teststart () throws IOException {//config file path String confpath = "mybatis-conf        Ig.xml ";        Read the configuration file to get the input stream InputStream InputStream = Resources.getresourceasstream (Confpath);        Create SQL Session Factory object Sqlsessionfactory sqlsessionfactory = new Sqlsessionfactorybuilder (). Build (InputStream);        Establish a session with the database sqlsession = Sqlsessionfactory.opensession (); The resulting is a dynamic proxy class Studentmapper = Sqlsession.getmapper (StudentmappeR.class);        } @Test public void Testinsertstu () {Student Student = new Student ();        Student.setsname ("Milen");        Student.setage (20);        Student.setsex ("female");        Student.setaddress ("Shenzhen");        int result = Studentmapper.insertstu (student);        Assert.assertnotequals (result, 0);    Sqlsession.commit ();        } @Test public void Testdelstu () {int result = Studentmapper.delstu (23);        Assert.assertnotequals (result, 0);    Sqlsession.commit ();        } @Test public void Testselectbyid () {Student Student = Studentmapper.selectbyid (2);        Assert.assertnotnull (student);        Jsonobject Stujson = new Jsonobject (student);        Assert.assertnotnull (Stujson);    System.out.println (Stujson);        } @Test public void Testselectall () {list<student> students = Studentmapper.selectall ();        Assert.assertnotequals (Students.size (), 0);        Assert.assertnotnull (students); System.out.println ("ID\tsname\tage\tsex\taddress ");            for (Student student:students) {System.out.print (Student.getsid () + "\ T");            System.out.print (Student.getsname () + "\ T");            System.out.print (Student.getage () + "\ T");            System.out.print (Student.getsex () + "\ T");        System.out.print (student.getaddress () + "\ n"); }} @Test public void Testselectbylimit () {list<student> students = studentmapper.selectbylimit (0,        5);        Assert.assertnotequals (Students.size (), 0);        Assert.assertnotnull (students);        System.out.println ("id\tsname\tage\tsex\taddress");            for (Student student:students) {System.out.print (Student.getsid () + "\ T");            System.out.print (Student.getsname () + "\ T");            System.out.print (Student.getage () + "\ T");            System.out.print (Student.getsex () + "\ T");        System.out.print (student.getaddress () + "\ n"); }} @Test public void Testupdatestu() {Student Student = new Student ();        Student.setsid (7);        Student.setsname ("Mkans");        Student.setage (23);        Student.setsex ("male");        Student.setaddress ("Hunan");        int result = Studentmapper.updatestu (student);        Assert.assertnotequals (result, 0);    Sqlsession.commit (); }//Close resource @After public void Testend () {if (sqlsession! = null) {//End session with database Sqls        Ession.close (); }    }}

Result mapping

In addition to the configuration of the basic SQL statement, we can also configure the result map with annotations, such as the following example:

@Select("select * from student")@Results({        @Result(id = true, property = "sid",column = "sid"),        @Result(property = "sname",column = "sname"),        @Result(property = "age",column = "age"),        @Result(property = "sex",column = "sex"),        @Result(property = "address",column = "address")})public List<Student> selectAll();

Note: @Results annotations correspond to the labels in the XML configuration file &lt;resultMap&gt; .

We can configure a one-to-many connection query in an XML configuration file, but we need to set the mapping of the result set to the field through the tag. We cannot do this in the annotations because there is no corresponding annotation support. But we can first configure the mapping relationship in XML and then refer to it by @resultmap annotations. The following example:

<?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 namespace= "Org.zero01.mapper.StudentMapper" > <resultmap id= "stumap" type= "Student" > <id P roperty= "Sid" Column= "Sid"/> <result property= "sname" column= "sname"/> <result property= "age" co Lumn= "Age"/> <result property= "sex" column= "sex"/> <result property= "Address" column= "Address"/&        Gt <association property= "Studentlog" resultmap= "Stulogmap"/> </resultMap> <resultmap id= "Stulogmap" Typ         E= "Studentlog" > <id property= "log_id" column= "log_id"/> <result property= "Sid" Column= "Sid"/> <result property= "sname" column= "sname"/> <result property= "age" column= "age"/> <resu Lt property= "sex" column= "sex"/> <result property= "Address" column= "addrESS "/> <result property=" Operation_type "column=" Operation_type "/> <result property=" Log_time "C olumn= "Log_time"/> </resultMap></mapper>

The annotation configuration reads as follows:

@Select("select * from student stu inner join studentlog stulog on  stu.`sid`=stulog.`sid`")@ResultMap("org.zero01.mapper.StudentMapper.stuMap")  // 引用XML里配置的映射器public List<Student> selectInnerLog();
Interface is used in conjunction with XML

Typically, we use a mix of interfaces with XML configuration files, which is simpler than plain XML or pure annotations.

Delete the annotations of the interface code as follows:

package org.zero01.mapper;import org.zero01.pojo.Student;import java.util.List;public interface StudentMapper {    public int insertStu(Student student);    public int delStu(int sid);    public Student selectById(int sid);    public List<Student> selectAll();    public List<Student> selectByLimit(int startRow, int endRow);    public int updateStu(Student student);    public List<Student> selectInnerLog();}

Then, in the MyBatis configuration file, add the following:

<mappers>    <mapper class="org.zero01.mapper.StudentMapper"/>    <mapper resource="org/zero01/mapper/StudentMapper.xml"/></mappers>

The new Studentmapper.xml file contains the following:

<?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 namespace= "Org.zero01.mapper.StudentMapper" > <resultmap id= "stumap" type= "Student" > <id P roperty= "Sid" Column= "Sid"/> <result property= "sname" column= "sname"/> <result property= "age" co Lumn= "Age"/> <result property= "sex" column= "sex"/> <result property= "Address" column= "Address"/&        Gt <association property= "Studentlog" resultmap= "Stulogmap"/> </resultMap> <resultmap id= "Stulogmap" Typ         E= "Studentlog" > <id property= "log_id" column= "log_id"/> <result property= "Sid" Column= "Sid"/> <result property= "sname" column= "sname"/> <result property= "age" column= "age"/> <resu Lt property= "sex" column= "sex"/> <result property= "Address" column= "addrESS "/> <result property=" Operation_type "column=" Operation_type "/> <result property=" Log_time "C olumn= "Log_time"/> </resultMap> <select id= "Selectinnerlog" resultmap= "Stumap" > select * FROM Student Stu INNER join Studentlog stulog on Stu. ' Sid ' =stulog. ' Sid ' </select> <insert id= ' Insertstu ' parame Tertype= "Student" > INSERT into Student (sname,age,sex,address) VALUES (#{sname},#{age},#{sex},#{address}) </    insert> <delete id= "Delstu" parametertype= "int" > delete from student where sid=#{0} </delete>    <select id= "Selectbyid" parametertype= "int" resulttype= "Student" > select * from Student where sid=#{0} </select> <select id= "SelectAll" resulttype= "Student" > select * from Student </select> & Lt;update id= "Updatestu" parametertype= "Student" > Update Student set sname=#{sname},age=#{age},sex=#{sex},addres S=#{address} where sid=#{SID} </update></mapper> 

Note: The value of the label ID attribute needs to correspond to the name of the interface method.

MyBatis using annotations on interfaces to configure SQL statements and interfaces to use with XML

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.