MyBatis基本的使用方法
1.新建Maven工程
2.导入MyBatis依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<dependencies>
<!-- Junit测试框架,用作方法测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- MyBatis核心依赖,就这一个 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!-- MySQL数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
3.MyBatis全局配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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>
<!-- 引入外部配置文件之后,就可以通过${}引入属性了 -->
<properties resource="jdbc.properties"/>
<!-- 配置环境为开发环境,当然还包括测试,生产 -->
<environments default="development">
<environment id="development">
<!-- 事务管理器,使用了 JDBC 的提交和回滚设置,依赖于从数据源得到的连接来管理事务范围 -->
<transactionManager type="JDBC"/>
<!-- 数据源,POOLED标识带数据源的,会使用MyBatis默认的数据连接池,UNPOOLED就是不带的,尽量带数据源,因为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="org/mybatis/example/UserMapper.xml"/>
</mappers>
</configuration>
4.jdbc.properties
1
2
3
4
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8
jdbc.username=root
jdbc.password=ww2711554770
5.创建UserMapper.xml和UserMapper接口
1
2
3
4
5
6
7
8
9
10
<?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="org.flameking.mybatis.mapper.UserMapper">
<!--int insertUser();-->
<insert id="insertUser">
insert into employee values(null,'张三',18,0)
</insert>
</mapper>
1
2
3
public interface UserMapper {
int insertUser();
}
6.测试文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class UserMapperTest {
@Test
public void insertUser() throws IOException {
// Resource时MyBatis提供的外部配置文件加载类
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
// SqlSession sqlSession = sqlSessionFactory.openSession(); 此时通过sqlSession对象操作的sql需要手动提交或回滚事务
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 创建动态代理的mapper对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int count = mapper.insertUser();
System.out.println("count:"+count);
}
}