01|简介
MyBatis是一款优秀的基于ORM的半自动轻量级持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。MyBatis可以使用简单的XML或注解来配置和映射原生类型、接口和Java的POJO为数据库中的记录。
02|构建
引入maven依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
创建配置文件
<?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="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
创建Mapper.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="white.colde.mapper.UserMapper">
<select id="selectUser" resultType="white.colde.entity.User">
select * from user where id = #{id}
</select>
</mapper>
创建映射实体
public class User{
private String username;
private String age;
private String sex;
// getter setter ....
}
创建映射器接口
public interface UserMapper{
User selectUser(Integer id)
}
构建使用
public class MapperTest {
@Test
public void mapperTest() throws IOException {
final SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
final SqlSession sqlSession = factory.openSession();
final UserMapper mapper = sqlSession.getMapper(UserMapper.class);
final User user = mapper.selectUser(1);
}
}
03|Java API
SqlSessionFactoryBuilder
用于构建SqlSessionFactory实例,生命周期为构建完即销毁。
SqlSessionFactory
SqlSession
包含了所有执行语句、提交或回滚事务以及获取映射器实例的方法,包含以下几类:
语句执行方法
<T> T selectOne(String statement, Object parameter)
<E> List<E> selectList(String statement, Object parameter)
<T> Cursor<T> selectCursor(String statement, Object parameter)
<K,V> Map<K,V> selectMap(String statement, Object parameter, String mapKey)
int insert(String statement, Object parameter)
int update(String statement, Object parameter)
int delete(String statement, Object parameter)
事务控制方法
void commit()
void commit(boolean force)
void rollback()
void rollback(boolean force)
获取映射器
<T> T getMapper(Class<T> type)