<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
2.在utils目录下目录下建立一个MybatisUtils类,通过这个工具类获得一个sqlSession.
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
3.在resources目录下添加对 MyBatis 系统的核心设置的XML 配置文件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="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--每写一个接口实现xml文件,都需要在这里配置相应的xml路径,现在先不写
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
-->
</configuration>
4.在resources目录下添加一个db.properties文件,进行数据库的配置,
driver=org.postgresql.Driver
url=jdbc:postgresql://localhost:5432/postgres
username=username
password=123456
并在mybatis-config.xml中添加
5.在dao目录下建立对应的接口和实现类。不过使用了Mybatis后,用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">
<!--namespace指向的是dao接口文件的路径-->
<mapper namespace="org.mybatis.example.BlogMapper">
<!--id指向接口的方法名,resultType指向pojo包下的类名路径-->
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
6.测试函数
public void text() {
//第一步获取SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//方法一
//第二步执行SQL语句
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
//方法二
//淘汰了//List<User> userList=sqlSession.selectList("com.huang.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭资源
sqlSession.close();
}