Mybatis interface annotation

Posted by ziggy3000 on Fri, 10 May 2019 14:22:03 +0200

In the previous chapter, we have built the development environment of myeclipse, mybatis and mysql, and implemented a simple query of mybatis. Note that this approach uses SqlSession instances to directly execute the SQL statements mapped in the User.xml file:
session.selectOne("com.yiibai.mybatis.models.UserMapper.getUserByID", 1), but there is a simpler way to use interfaces that reasonably describe parameters and return values of SQL statements (e.g. IUser.class), so that you can now avoid configuration files similar to User.xml, which are simpler, safer, and less prone to string text and conversion errors, as follows It is the detailed process of project creation:

Use Interface + Annotation

1. Create an interface: IUser, in which you declare the corresponding method of operation.

Create a package under the src source directory: com.yiibai.mybatis.dao, and establish the interface class IUser and a method. In terms of the method, we use an SQL annotation, which reads as follows:

package com.yiibai.mybatis.dao;

import org.apache.ibatis.annotations.Select;

import com.yiibai.mybatis.models.User;

public interface IUser {
    //Interface + Annotation
    @Select("select * from user where id= #{id}")
    public User getUserByID(int id);
}

2. Create corresponding mapping interface SQL statements

First, configure the data connection file required by MyBatis, and create a file: src/config/Configure.xml, which reads 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.dtd">
<configuration>
    <typeAliases>
        <typeAlias alias="User" type="com.yiibai.mybatis.models.User" />
    </typeAliases>
    <environments default="development">
        <environment id="development">
        <transactionManager type="JDBC" />
            <dataSource type="POOLED">  
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/yiibai" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

    <!-- When using annotations, you do not need to configure the mapping file -->
    <mappers>
         <!-- // power by http://www.yiibai.com -->
    </mappers>
</configuration>

Create a User.java class file under the package: com.yiibai.mybatis.models, which is the same as the User class code in the previous section. Here is just a copy. The specific code of User.java is as follows:

package com.yiibai.mybatis.models;

public class User {
    private int id;
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    private String dept;
    private String phone;
    private String website;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getDept() {
        return dept;
    }
    public void setDept(String dept) {
        this.dept = dept;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getWebsite() {
        return website;
    }
    public void setWebsite(String website) {
        this.website = website;
    }
}

The XML configuration file corresponding to User.java: User.xml can be omitted less and need not be created. This section explains how to eliminate configuration files similar to User.xml.

3. Test Interface Mapping

In the src directory, we create a class: Main.java, which is used to test the entire configuration and program running results. The code for Main.java is as follows:

import java.io.Reader;

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 com.yiibai.mybatis.dao.IUser;
import com.yiibai.mybatis.models.User;

public class Main {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources
                    .getResourceAsReader("config/Configure.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(reader);

            //When using annotations, you don't need to use mapping files, but you need to add interface classes here.
            sqlSessionFactory.getConfiguration().addMapper(IUser.class);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SqlSession session = sqlSessionFactory.openSession();
        try {

            //Get an instance of the interface class
            IUser iUser = session.getMapper(IUser.class);
            User user = iUser.getUserByID(1);

            System.out.println("Name:"+user.getName());
            System.out.println("Departments:"+user.getDept());
            System.out.println("Home page:"+user.getWebsite());
        } finally {
            session.close();
        }
    }

}

Run the sample code above to get the following results-

Name: New name, Department: Tech, Home page: http://www.yiibai.com

Finally, the whole project mybatis-interface-02 is structured as follows:

Topics: Mybatis xml Session Java