用mybatis实现简单的CRUD

  下面介绍如何用mybatis实现简单的增删改查功能,有两种方式,一种是通过xml配置文件实现,一种是通过注解实现。
  
仍然通过对user的操作进行说明,新建好项目并导入jar包后,新建数据库和表,并插入两条记录:

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_1b4bbvojp1ilqqsu1ad9105783f9.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 + "]";
}
}

通过XML实现

新建映射文件userMapper.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
28
29
30
31
32
33
<?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.test2.userMapper">
<!-- 添加操作 -->
<insert id="addUser" parameterType="com.mybatis.entities.User">
insert into users(name,age)
values(#{name},#{age})
</insert>
<!-- 删除操作 -->
<delete id="deleteUser" parameterType="int">
delete from users where
id=#{id}
</delete>
<!-- 更新操作 -->
<update id="updateUser" parameterType="com.mybatis.entities.User">
update users set name = #{name},age = #{age} where id = #{id}
</update>
<!-- 根据id查找单个记录 -->
<select id="getUserById" parameterType="int"
resultType="com.mybatis.entities.User">
select *
from users where id=#{id}
</select>
<!-- 查找所有记录 -->
<select id="getAllUsers" resultType="com.mybatis.entities.User">
select * from users
</select>
</mapper>

在mybatis配置文件中注册上述映射文件:

1
2
3
<mappers>
<mapper resource="com/mybatis/test2/userMapper.xml" />
</mappers>

编写测试类进行测试:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class Test {
private SqlSessionFactory sessionFactory;
private SqlSession session;
@Before
public void init(){
//读取配置文件
String resource = "conf.xml";
InputStream is = this.getClass().getClassLoader().getResourceAsStream(resource);
//创建SqlSessionFactory和SqlSession
sessionFactory = new SqlSessionFactoryBuilder().build(is);
session = sessionFactory.openSession();
}
@After
public void free(){
session.commit();
session.close();
}
@org.junit.Test
public void testAddUser() {
String statement = "com.mybatis.test2.userMapper"+".addUser";
User user = new User(-1, "Alan", 25);
session.insert(statement, user);
}
@org.junit.Test
public void testDeleteUser() {
String statement = "com.mybatis.test2.userMapper"+".deleteUser";
session.delete(statement, 3);
}
@org.junit.Test
public void testUpdateUser() {
String statement = "com.mybatis.test2.userMapper"+".updateUser";
User user = new User(2,"Jim",19);
session.update(statement, user);
}
@org.junit.Test
public void testgetUserById() {
String statement = "com.mybatis.test2.userMapper"+".getUserById";
User user = session.selectOne(statement, 1);
System.out.println(user);
}
@org.junit.Test
public void testgetAllUsers() {
String statement = "com.mybatis.test2.userMapper"+".getAllUsers";
List<User> list = session.selectList(statement);
System.out.println(list);
}
}

注意点:

  1. 在映射文件中,当parameterType=”int”时,sql语句中的参数名可以随便定义,例如#{id},#{_id}都可以;但是当parameterType=”com.mybatis.entities.User”时,sql语句中的参数名需要和User类中的对应字段名一致,例如#{id}对应User类中的字段id,而不能写成#{_id}。
  2. 在映射文件中定义getAllUsers时,只需要指明返回的集合中的元素的类型,即仅需要指明resultType=”com.mybatis.entities.User”就可以了。

通过注解实现

新建接口UserMapper.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface UserMapper {
@Insert("insert into users(name,age) values(#{name},#{age})")
public int addUser(User user);
@Delete("delete from users where id=#{id}")
public int deleteUser(int id);
@Update("update users set name=#{name},age=#{age} where id=#{id}")
public int updateUser(User user);
@Select("select * from users where id=#{id}")
public User getUserById(int id);
@Select("select * from users")
public List<User> getAllUsers();
}

在mybatis配置文件中注册该接口:

1
2
3
<mappers>
<mapper class="com.mybatis.test3.UserMapper"/>
</mappers>

编写测试列进行测试:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class Test {
private SqlSessionFactory sessionFactory;
private SqlSession session;
private UserMapper userMapper;
@Before
public void init(){
//读取配置文件
String resource = "conf.xml";
InputStream is = this.getClass().getClassLoader().getResourceAsStream(resource);
//创建SqlSessionFactory和SqlSession
sessionFactory = new SqlSessionFactoryBuilder().build(is);
session = sessionFactory.openSession();
//获取UserMapper
userMapper = session.getMapper(UserMapper.class);
}
@After
public void free(){
session.commit();
session.close();
}
@org.junit.Test
public void testAddUser() {
User user = new User(-1, "Alan", 25);
userMapper.addUser(user);
}
@org.junit.Test
public void testDeleteUser() {
userMapper.deleteUser(9);
}
@org.junit.Test
public void testUpdateUser() {
User user = new User(2,"Jim",19);
userMapper.updateUser(user);
}
@org.junit.Test
public void testgetUserById() {
User user = userMapper.getUserById(1);
System.out.println(user);
}
@org.junit.Test
public void testgetAllUsers() {
List<User> list = userMapper.getAllUsers();
System.out.println(list);
}
}

可以优化的地方

一、连接数据库的配置单独放在一个properties文件中:

新建配置文件db.properties:

1
2
3
4
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
name=你的数据库用户名
password=你的数据库密码

在mybatis配置文件中配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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="db.properties"/>
<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="${name}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<mappers>
...
</mappers>
</configuration>

二、 可以为实体类定义别名,以简化映射文件中的引用:

在mybatis配置文件的configuration节点下配置:

1
2
3
<typeAliases>
<typeAlias type="com.mybatis.entities.User" alias="User"/>
</typeAliases>

那么,当要在映射文件引用User类的全类名时,只需要使用”User”即可,例如:

1
2
3
4
5
<!-- 添加操作 -->
<insert id="addUser" parameterType="User">
insert into users(name,age)
values(#{name},#{age})
</insert>

当要定义别名的类比较多时,还有一种更方便的方法,在mybatis配置文件的configuration节点下配置:

1
2
3
<typeAliases>
<package name="com.mybatis.entities"/>
</typeAliases>

这将声明在映射文件中,包com.mybatis.entities下的所有类都可以用简单类名来替代全类名。

三、可以在src下加入log4j的配置文件,打印日志信息:

首先需要先导入log4j的jar包:

image_1b4br2p5dqlm1urr5531d9q1g4o9.png-3.5kB

然后配置log4j,有两种方法:

方法一、在src目录下新建log4j.properties:

1
2
3
4
5
6
7
8
9
10
11
log4j.properties,
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

方法二、在src目录下新建log4j.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="debug" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>

然后当执行sql操作时就会在控制台打印sql语句。

解决字段名与实体类属性名不相同的冲突

  在上面的例子中,我们在映射文件中按一下方式定义select操作时:

1
2
3
4
5
<select id="getUserById" parameterType="int"
resultType="User">
select *
from users where id=#{id}
</select>

之所以能够查找成功并成功返回一个User对象,是因为实体类User的字段名和表users的列名完全一致:

User类:
image_1b4bsgsuo1skrrcgp711djtr213.png-4.7kB

users表:
image_1b4bsjji91o9t1pd01rp47oi11s71t.png-6.5kB

当它们不一致时,就无法通过这种方式达到预期的效果。这个问题有两种解决办法,为了进行说明,我们先定义列名和字段名不一致的表orders和类Order:
  
新建表,并插入三条记录:

1
2
3
4
5
6
7
8
CREATE TABLE orders(
order_id INT PRIMARY KEY AUTO_INCREMENT,
order_no VARCHAR(20),
order_price FLOAT
);
INSERT INTO orders(order_no, order_price) VALUES('aaaa', 23);
INSERT INTO orders(order_no, order_price) VALUES('bbbb', 33);
INSERT INTO orders(order_no, order_price) VALUES('cccc', 22);

image_1b4bs0168efh1v42ohqlj414fum.png-10.4kB

新建实体类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Order {
private int id;
private String orderNo;
private float price;
//getters and setters
@Override
public String toString() {
return "Order [id=" + id + ", orderNo=" + orderNo + ", price=" + price + "]";
}
public Order(int id, String orderNo, float price) {
super();
this.id = id;
this.orderNo = orderNo;
this.price = price;
}
public Order() {
super();
}
}

  在这个例子中,orders表的列为order_id,order_no,order_price,Order类的对应字段名分别为id,orderNo,price,解决方法如下:
  
方法一、通过在映射文件的sql语句中定义别名:

1
2
3
<select id="getOrder" parameterType="int" resultType="Order">
select order_no orderNo,order_price price from orders where order_id=#{id}
</select>

方法二: 通过映射文件中节点的resultMap属性:

1
2
3
4
5
6
7
8
9
<select id="getAllOrders" resultMap="orderResultMap">
select * from orders
</select>
<resultMap type="Order" id="orderResultMap">
<id property="id" column="order_id" />
<result property="orderNo" column="order_no" />
<result property="price" column="order_price"/>
</resultMap>

其中,select节点中的resultMap需要和resultMap节点的id对应。在resultMap节点下,主键使用id节点,普通属性使用result节点,其中property指实体类中的字段名,column指数据库表中对应的列名。