Mybatis笔记01--环境搭建
Mybatis笔记01--环境搭建
获取Mybatis
- maven仓库
1 |
|
- github: https://github.com/mybatis/mybatis-3/releases
- 中文文档:https://mybatis.org/mybatis-3/zh/index.html
搭建环境
1. 创建数据库
1 |
|
2. 创建maven项目,并导入maven依赖
1 |
|
3. 创建一个模块module
编写mybatis的核心配置文件
1 |
|
编写mybatis工具类
1 |
|
编写代码
编写实体类
编写接口
1
2
3public interface UserDao {
List<User> getUserList();
}接口实现类由原来的***Impl转换为一个Mapper配置文件
1
2
3
4
5
6
7
8
9<?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.lics.dao.UserDao">
<select id="getUserList" resultType="com.lics.pojo.User">
select * from mybatis.user
</select>
</mapper>每一个Mapper.XMl都需要在mybatis的核心配置文件中注册!
1
2
3<mappers>
<mapper resource="com/lics/dao/UserMapper.xml" />
</mappers>测试代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16public class UserDaoTest {
@Test
public void test01() {
// 获取sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 执行SQL
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
System.out.println(userList);
sqlSession.close();
}
}
4. xml文件导出失败:
在pom文件中增加以下设置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21<!--maven的资源过滤问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!