mybatis快速入门

Mybatis简介

  MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。   

Mybatis快速入门

下面写一个简单的测试例子,首先新建一个project,导入mybatis核心jar包和mysql驱动jar包:
image_1b4adm56plbu1d1bgvv8p21fdu9.png-4.6kB

新建数据库和表,并插入两条记录:

1
2
3
4
5
create database mybatis;
use mybatis;
CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT);
INSERT INTO users(NAME, age) VALUES('Tom', 12);
INSERT INTO users(NAME, age) VALUES('Jack', 11);

建表成功:
image_1b4aeseal1l64lvmiht1b391ns913.png-14kB

新建实体类User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.mybatis.entities;
public class User {
private Integer id;
private String name;
private Integer age;
//getters and setters
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}

新建实体类的映射文件userMapper.xml

1
2
3
4
5
6
7
8
9
10
11
<?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.mybatis.entities.userMapper">
<!-- 定义一个查询,根据id查询到一条users记录 -->
<!-- parameterType指定sql语句的#{id}中id类型为int -->
<!-- resultType指定将查询结果封装到一个User类中进行返回 -->
<select id="getUser" parameterType="int"
resultType="com.mybatis.entities.User">
select * from users where id=#{id}
</select>
</mapper>

在src目录下新建mybatis配置文件conf.xml:

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
27
<?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>
  
  <!-- 可选development:开发模式,work:工作模式 -->
<environments default="development">
<environment id="development">
  <!-- 事务管理,使用JDBC的提交和回滚设置 -->
<transactionManager type="JDBC" />
<!-- 配置数据源,使用连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="你的数据库用户名" />
<property name="password" value="你的数据库密码" />
</dataSource>
</environment>
</environments>
<!-- 注册映射文件 -->
<mappers>
<mapper resource="com/mybatis/entities/userMapper.xml"/>
</mappers>
</configuration>

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Test {
@org.junit.Test
public void test() {
//读取配置文件
String resource = "conf.xml";
InputStream is = this.getClass().getClassLoader().getResourceAsStream(resource);
//创建SqlSessionFactory和SqlSession
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession();
//映射sql的标识字符串
//com.mybatis.entities.userMapper对应映射文件中的namespace
//getUser对应映射文件中的select标签的id
String statement = "com.mybatis.entities.userMapper"+".getUser";
//执行查询返回id为1的记录
User user = session.selectOne(statement, 1);
System.out.println(user);
}
}

运行结果如下图所示:
image_1b4agku565uour7v9ub851m4q1g.png-5.2kB