版权声明:本文为博主ExcelMann的原创文章,未经博主允许不得转载。
2、第一个MyBatis程序
作者:ExcelMann,转载需注明。
思路:首先搭建环境->导入Mybatis包->编写代码->测试
2.1、搭建环境
1、搭建数据库
create database `mybatis`;
use `mybatis`;
create table `user`(
`id` int(20) not null primary key,
`name` varchar(20) default null,
`pwd` varchar(20) default null
)engine=InnoDB default charset=utf8;
insert into `user`(`id`,`name`,`pwd`) values
(1,'excelman','123456'),
(2,'excelman2','123456'),
(3,'excelman3','123456')
2、新建普通的maven项目,并把src
目录删掉,作为一个父工程
3、在pom.xml文件中导入maven依赖(jdbc、mybatis、junit)
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
2.2、创建一个子工程
1、编写mybatis核心配置文件: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="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="a8954214"/>
</dataSource>
</environment>
</environments>
</configuration>
2、编写mybatisUtils类,构建SqlSessionFactory,并返回SqlSession对象
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static{
try {
// maven下可以直接读取该文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例
//SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
2.3、编写代码
- pojo实体类:User类
- Dao接口:UserDao接口(后面更名为UserMapper接口)
public interface UserDao {
List<User> getUserList();
}
- 接口实现类:Mybatis的接口实现类由以往的
UserDaoImpl
转换为一个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">
<!-- namespace绑定一个对应的Dao/Mapper接口 -->
<mapper namespace="com.Excelman.dao.UserDao">
<!-- id对应UserDao接口的方法 -->
<select id="getUserList" resultType="com.Excelman.pojo.User">
select * from mybatis.user
</select>
</mapper>
注意:在mybatis-config.xml配置文件中,记得配置mapper
<!--配置每个Mapper-->
<mappers>
<mapper resource="com/Excelman/dao/UserMapper.xml" />
</mappers>
2.4、测试
采用Junit测试。
public class UserDaoTest {
@Test
public void test(){
// 获取sqlsession
SqlSession sqlSession = MybatisUtils.getSqlSession();
// 通过sqlsession获取mapper
UserDao mapper = sqlSession.getMapper(UserDao.class);
// 调用mapper的方法,执行sql
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
}
2.5、注意的坑
-
pom.xml文件中,注意要加上过滤器设置,以防xml文件被过滤,加载不了;
(备注:如果改完还是不行,试着先将maven clean一下,然后重载maven项目)
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
- resources文件夹下的文件,在生成target目标文件后,自动放在根目录下,所以可以直接读取,不需要全路径;
- 写完每一个Mapper(实现Dao接口的配置文件)后,必须在mybatis-config.xml中配置;且如果配置的时候,选择填写resource的话,要写路径’’/’’;
<!--配置每个Mapper-->
<mappers>
<mapper resource="com/Excelman/dao/UserMapper.xml" />
</mappers>
- sqlsession用完记得close关闭;
2.6、Mybatis内部实现步骤
- Resources获取加载全局配置文件
- 实例化SqlSessionFactoryBuilder构造器
- 解析配置文件流XMLConfigBuilder
- Configuration所有的配置信息
- SqlSessionFactory实例化
- transactional事务管理
- 创建executor执行器(重点)
- 创建sqlSession
- 实现CRUD