Mybatis framework learning (1)-Mybatis framework configuration

Posted May 25, 20202 min read

Mybatis framework

MyBatis is a persistence layer framework that implements encapsulation of JDBC operations. It is mainly used to simplify some relatively cumbersome steps in JDBC operations, such as parameter mapping and result set mapping.

MyBatis configuration

  1. Add dependencies

    MYSQL driver dependency

    mysql mysql-connector-java 5.1.40

    Mybatis framework dependency

    org.mybatis mybatis 3.4.6
  2. Configuration items
    Create mybatis-config.xml under resource

    <! DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0 //EN"
    " http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!-mybatis core configuration->

3. Test procedure
public class TestMybatis {

/**
* Create SqlSession with the help of this object(through this object
* To achieve a conversation with the database)
* /
protected SqlSessionFactory factory;
/**
* This method will be executed before the method modified by @Test annotation,
* Usually used to do some initialization operations(the method name is defined by yourself)
* /
@Before
public void init() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-configs.xml");
factory = new SqlSessionFactoryBuilder(). build(in);
//The system bottom builder mode builds factory objects(this object construction process is relatively complicated)
System.out.println(factory);
}
@Test
public void testSqlSessionConnection() {
SqlSession session = factory.openSession();
Connection conn = session.getConnection();
System.out.println(conn);
}

}

  1. Test results

    org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@516be40f
    com.mysql.jdbc.JDBC4Connection@7e0b85f9

Business logic test

Create Mapper folder under Resource and create mybatis configuration file SysLogMapper.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 = "com.company.SysLogMapper">
<cache />
<delete id = "deleteObject">
delete from sys_logs where id = # {id}
</delete>
<select id = "findPageObject" resultType = "Object">
    select id, createdTime from sys_logs
    limit # {startIndex}, # {pageSize}
</select>
</mapper>