Chapter 2 Introduction to MyBatis

Keywords: Programming Mybatis xml Database MySQL

Simple Edition

  • Create a test table
  • Create the corresponding JavaBean
  • Create mybatis configuration file and sql mapping file
  • test

MyBatis operation database

  • Create MyBatis global profile

The global configuration file of MyBatis contains settings and properties information, such as database connection pool information, which affect MyBatis' behavior deeply. Guide MyBatis in their work. We can refer to the configuration example of the official file.

  • Create SQL map file

The purpose of the mapping file is to define how the implementation classes of the Dao interface work. This is the most written file we use MyBatis.

  • According to the global configuration file, use SqlSessionFactoryBuilder to create SqlSessionFactory.
String resource="mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is);
  • Get the SqlSession object using SqlSessionFactory. A SqlSession object represents a session with the database.
SqlSession sqlSession = sf.openSession();

Use SqlSession: query by Id

SqlSession sqlSession = sf.openSession();
try {
    Employee employee = sqlSession.selectOne("helloworld.EmployeeMapper.getEmployeeById", 1);
    System.out.println(employee);
} finally {
    sqlSession.close();
}

Full code

  • Add related maven dependencies
<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.19</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.7</version>
    </dependency>
</dependencies>
  • Script database
create table t_employee(
      id int auto_increment,
      last_name varchar(255),
      email varchar(255),
      gender varchar(255),
      primary key(id)
);

insert into t_employee (last_name,email,gender)values('tom','tom@qq.com','male');

select * from t_employee;
  • Write entity class
public class Employee {

    private Integer id;
    private String lastName;
    private String email;
    private String gender;

    // getter and setter

    // toString
}
  • to write EmployeeMapper.xml
<?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="helloworld.EmployeeMapper">
    <!--
    namespace: Namespace. Is the full class name of the interface.
    id: Unique identification.
    resultType: Return value type.
    #{id}: take the id value from the passed parameter

    public Employee getEmpById(Integer id);
     -->
    <select id="getEmployeeById" resultType="helloworld.Employee">
        select 
            id,
            last_name lastName,
            email,gender
        from t_employee
        where id = #{id}
    </select>
</mapper>
  • Write the global configuration file MyBatis for mybatis-config.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"/>
            <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>
    </environments>
    <!-- To be written sql Mapping files( EmployeeMapper.xml)Be sure to register to the global profile( mybatis-config.xml)in -->
    <mappers>
        <mapper resource="helloworld/EmployeeMapper.xml"/>
    </mappers>
</configuration>
  • Write main program
public class Test {
    public static void main(String[] args) throws IOException {
        String resource = "mybatis-config.xml";
        InputStream is = Resources.getResourceAsStream(resource);
        SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is);
       
        SqlSession sqlSession = sf.openSession();
        try {
            Employee employee = sqlSession.selectOne("helloworld.EmployeeMapper.getEmployeeById", 1);
            System.out.println(employee);
        } finally {
            sqlSession.close();
        }
    }
}

Interface programming

  • Create a Dao interface
public interface EmployeeMapper {
    Employee getEmployeeById(Integer id);
}

  • test
SqlSession sqlSession = sf.openSession();
try {
    // Using SqlSession to get mapper for operation
    EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
    Employee employee = mapper.getEmployeeById(1);
    System.out.println(employee);
} finally {
    sqlSession.close();
}

SqlSession

  • The instance of SqlSession is non thread safe, so it cannot be shared.
  • SqlSession needs to be closed properly after each use, which is necessary.
  • SqlSession can directly call the id of the method for database operation.

However, it is recommended to use SqlSession to get the proxy class of Dao interface. The method of executing the proxy object can perform type checking operations more safely.

Posted by sumolotokai on Tue, 16 Jun 2020 20:27:06 -0700