MyBatis 实用篇(一)入门
MyBatis(http://www.mybatis.org/mybatis-3/zh/index.html) 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。
MyBatis 消除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记录。
1. 引入 MyBatis
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
</dependencies>
2. 配置文件
<?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="dev">
<environment id="dev">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/github/binarylei/mybatis/helloworld/UserMapper.xml"/>
</mappers>
</configuration>
3. mapper 文件
<?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.github.binarylei.mybatis.helloworld.UserMapper">
<select id="getUser" resultType="com.github.binarylei.mybatis.helloworld.User">
select * from user where id=#{id};
</select>
</mapper>
4. 使用
4.1 xml 调用
public void test() {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
User user = sqlSession.selectOne("getUser", 1);
System.out.println(user);
} finally {
sqlSession.close();
}
}
4.2 接口调用
public interface UserMapper {
void getUser(User user);
}
public void test() {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = (User) userMapper.getUser(1);
System.out.println(user);
} finally {
sqlSession.close();
}
}
每天用心记录一点点。内容也许不重要,但习惯很重要!