Mybatis framework
Mybatis a persistence layer framework, which encapsulates 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 dependency
MySQL driver dependency
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
Mybatis framework dependency
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
2. Configuration items
Creating mybatis under resource- config.xml
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<! -- mybatis core configuration -- >
<configuration>
<! -- configure initialization environment (connection) --- >
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<! -- use mybatis's own connection pool -- >
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///jtsys"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
3. Test procedure
public class TestMybatis {
/**
*Create a sqlsession with this object
*Implement a session with the database)
*/
protected SqlSessionFactory factory;
/**
*This will be executed before the method decorated by the @ test annotation,
*It is usually used to do some initialization operations (the method name is defined by itself)
*/
@Before
public void init()throws IOException{
InputStream in=Resources.getResourceAsStream("mybatis-configs.xml");
factory=new SqlSessionFactoryBuilder().build(in);
//The factory object is constructed by the bottom builder mode of the system (the construction process of this object is relatively complex)
System.out.println(factory);
}
@Test
public void testSqlSessionConnection(){
SqlSession session=factory.openSession();
Connection conn=session.getConnection();
System.out.println(conn);
}
}
4. Test results
[email protected]e40f
[email protected]
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>