Fork me on GitHub

二、MyBatis入门示例

img

二、MyBatis入门示例


在本篇博客中,我们来一起完成MyBatis的入门示例

准备数据库和表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
DROP TABLE student;

CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
gender VARCHAR(10),
birthday DATE
);


INSERT INTO student (name,gender,birthday) VALUES ('波多结衣','female','1995-12-11');
INSERT INTO student (name,gender,birthday) VALUES ('波少结衣','female','1996-11-12');
INSERT INTO student (name,gender,birthday) VALUES ('杉原杏璃','female','1997-10-13');
INSERT INTO student (name,gender,birthday) VALUES ('佐佐木希','female','1998-09-14');
INSERT INTO student (name,gender,birthday) VALUES ('伊藤梅子','female','1999-08-15');
12345678910111213141516

我们建立数据库mb,并创建一张表student并为其插入数据。

创建JavaBean

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

package cn.com.helloworld;

import java.util.Date;

public class Student {
private int id;
private String name;
private String gender;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", gender=" + gender
+ ", birthday=" + birthday + "]";
}

}

请注意:将JavaBean中的字段与数据库中表中的字段保持一致

导入MyBatis相关jar包

请下载MyBatis开发所需jar包并存放至工程的lib目录。

SqlMapConfig.xml

在有了数据库和JavaBean之后我们来编写MyBatis的全局配置文件SqlMapConfig.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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/mb?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
12345678910111213141516

在该配置文件中配置由MyBatis所采用的事务和数据库连接池

StudentMapper.xml

刚才我们编写了MyBatis的全局配置文件SqlMapConfig.xml,现在我们来编写与JavaBean相关的配置文件StudentMapper.xml

1
2
3
4
5
6
<?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="student">

</mapper>123456

我们在该配置文件中添加标签并设置其namespace为student。

再将StudentMapper.xml配置到SqlMapConfig.xml,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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/mb?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="sqlmap/StudentMapper.xml" />
</mappers>
</configuration>123456789101112131415161718

请参见代码第15—17行

CRUD操作

在完成了之上的准备工作后,我们来利用MyBatis实现简单的增删改查。

我们先来做一个最简单的例子:依据Stundet的id查询学生信息

首先在映射文件StudentMapper.xml中写sql语句:

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="student">

<select id="findStudentById" parameterType="int" resultType="cn.com.helloworld.Student">
SELECT * FROM student WHERE id=#{value}
</select>

</mapper>12345678910

在该xml文件中为我们的需求写了一个sql语句,请注意

  • id标识该sql语句的唯一性,因为之后随着功能的扩展在该xml文件中会有许多sql语句。其实,类似于StudentMapper.xml这样的mapper.xml文件中每一个sql语句都对应一个MappedStatement对象,sql语句的id即是MappedStatement的id。
  • parameterType表示输入参数类型。此处我们要依据id查询学生,那么输入参数就是一个int类型的数字
  • resultType表示查询结果的返回类型。在此,我们想得到一个Student对象,所以将resultType设置为cn.com.helloworld.Student
  • #{ }表示占位符,用于接收输入参数。输入参数的类型可以是简单类型,pojo、HashMap。如果输入参数是简单类型那么#{}的括号中可以写成value或其它名称。

在完成了映射文件的编码之后,我们再来书写Java代码

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
/**
* 本文作者:谷哥的小弟
* 博客地址:http://blog.csdn.net/lfdfhl
*/
package cn.com.helloworld;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

public class CRUDTest {
@Test
public void findStudentById() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Student student = sqlSession.selectOne("student.findStudentById", 1);
System.out.println(student);
sqlSession.close();
}
}

代码详解如下:

  • 获取MyBatis的全局配置文件SqlMapConfig.xml,请参见代码第18—19行
  • 利用全局配置文件创建SqlSessionFactory,请参见代码第20行
  • 利用SqlSessionFactory创建SqlSession,请参见代码第21行
  • 利用SqlSession调用其selectOne()方法查询一条学生信息,请参见代码第22行。请注意该方法参数:第一个参数用于标识一条sql语句,其构成为:映射文件的namespace+”.”+MappedStatement的id(即sql语句的id);第二参数是需要传递给sql语句的输入参数。
  • 关闭SqlSession,释放资源;请参见代码第24行

输出结果如下:

Student [id=1, name=波多结衣, gender=female, birthday=Mon Dec 11 00:00:00 CST 1995]

至此,我们走完了一个利用MyBatis查询数据的完整流程。

刚才这个例子是查询出来了单条记录,如果要查询多条记录又该怎么做呢?
比如查询出学生名字中带有”结”这个字的所有学生,请看如下代码:

1
2
3
<select id="findStudentByName" parameterType="java.lang.String" resultType="cn.com.helloworld.Student">
SELECT * FROM student WHERE name LIKE '%${value}%'
</select>

在该映射文件中采用${ }表示拼接,它所接收的输入参数类型可以是简单类型,pojo,HashMap。如果接收简单类型,${}中只能写成value。当${}接收pojo对象值时可通过OGNL读取对象中的属性值;即利用属性.属性.属性…的方式获取对象属性值

在完成映射文件的编写之后,我们再来看Java代码:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void findStudentByName() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<Student> list = sqlSession.selectList("student.findStudentByName", "结");
for(Student student:list){
System.out.println(student);
}
sqlSession.close();
}

在此利用了qlSession.selectList( )方法返回一个查询后的集合。

输出结果如下:

Student [id=1, name=波多结衣, gender=female, birthday=Mon Dec 11 00:00:00 CST 1995]
Student [id=2, name=波少结衣, gender=female, birthday=Tue Nov 12 00:00:00 CST 1996]

在完成查询操作后,我们向数据库插入一条新数据,并得到新数据被插入到数据库后它的主键值。

1
2
3
4
5
6
<insert id="insertStudent" parameterType="cn.com.helloworld.Student">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO student (name,gender,birthday) value (#{name},#{gender},#{birthday})
</insert>123456

我们在标签中使用了标签
获取插入数据的主键并将其设置到Student对象中.

  • SELECT LAST_INSERT_ID():得到insert记录的主键值,只适用与自增主键
  • keyProperty:用于指明将查询到的主键值设置到parameterType指定的对象的哪个属性
  • order:表示SELECT LAST_INSERT_ID()相对于insert语句的执行顺序。在该例子中用AFTER表示执行完该insert语句后再执行SELECT LAST_INSERT_ID()
  • resultType:指定SELECT LAST_INSERT_ID()的结果的类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
public void insertStudent() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Student student=new Student();
student.setName("右右木希");
student.setGender("female");
student.setBirthday(new Date());
sqlSession.insert("student.insertStudent",student);
sqlSession.commit();
sqlSession.close();
System.out.println(""+student.getId());
}

代码解析如下:

  • 利用sqlSession.insert()将数据插入数据库,请参见代码第11行
  • 利用sqlSession.commit()提交事务,请参见代码第12行
  • 获取到新插入数据的主键值,请参见代码第14行

继续来看删除数据的操作

1
2
3
<delete id="deleteStudent" parameterType="java.lang.Integer">
DELETE FROM student where id=#{id}
</delete>123

Java代码如下:

1
2
3
4
5
6
7
8
9
10
@Test
public void deleteStudent() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.delete("student.deleteStudent", 1);
sqlSession.commit();
sqlSession.close();
}12345678910

最后来瞅瞅更新操作

1
2
3
<update id="updateStudent" parameterType="cn.com.helloworld.Student">
UPDATE student set name=#{name},gender=#{gender},birthday=#{birthday} where id=#{id}
</update>123

Java代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
public void updateStudent() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
Student student=new Student();
student.setId(3);
student.setName("中中木希");
student.setGender("female");
student.setBirthday(new Date());
sqlSession.update("student.updateStudent", student);
sqlSession.commit();
sqlSession.close();
}123456789101112131415

嗯哼,至此我们关于MyBatis的入门示例就已经全部完成了。

项目结构图如下所示:

这里写图片描述

-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!