一、搭建MySQL环境
创建maven项目
导入maven依赖
mysql
mysql-connector-java
5.1.47
org.mybatis
mybatis
3.5.2
junit
junit
4.12
- 配置xml和properties文件的扫描方式
src/main/resources
**/*.properties
**/*.xml
true
src/main/java
**/*.properties
**/*.xml
true
- 完整pom.xml
4.0.0
com.yaco
mybatis
pom
1.0-SNAPSHOT
mybatis01
mybatis02
mybatis03
mysql
mysql-connector-java
5.1.47
org.mybatis
mybatis
3.5.2
junit
junit
4.12
src/main/resources
**/*.properties
**/*.xml
true
src/main/java
**/*.properties
**/*.xml
true
二、实现简单的增删改查
1、创建数据库
创建一个简单的用户表,表中含有三个属性,用户id,用户名和用户密码
CREATE DATABASE mybatis;
USE mybatis;
# 创建表
CREATE TABLE `user`(
`id` INT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
# 插入数据
INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'张三','123456'),
(2,'李四','123456'),
(3,'狂神','123456')
2、创建mybatis-config.xml
配置文件
主要配置数据连接的相关信息,包括驱动器、url、连接数据库的用户名和密码、是否启动数据库连接池等信息
使用mapper配置userMapper.xml的映射文件位置
3、创建对应的数据库中的实体类
实体类对应数据库中User表中的字符名,此处与表中字段名完全一致,也可以不一致
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
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 getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
创建UserMapper的持久层接口
public interface UserMapper {
// 查
List getUserList();
// 增
int addUser(User user);
// 删
void deleteById(int id);
// 该
int update(User user);
// 查找一个
User findById(int id);
// 根据用户名和密码查询,使用map
User findByNameAnsPwd(Map map);
// 模糊查询
List findUserLike(String value);
}
4、创建mapper映射文件
update user set name=#{name}, pwd=#{pwd} where id = #{id}
delete from user where id = #{id}
insert into user (id, name, pwd) values (#{id},#{name},#{pwd})
5、创建一个MybatisUtil工具类
MybatisUtil工具类用于获取执行映射文件中的sql语句的SqlSession
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
// 获取SqlSessionFactory对象
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
6、测试类
在test文件下做测试,保证包名与所测试的类包结构一致
public class UserDaoTest {
@Test
public void testList() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
List userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
@Test
public void testFindOne() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
User user = userDao.findById(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void testInsert() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(5);
user.setName("hj");
user.setPwd("123456");
int res = userDao.addUser(user);
if(res > 0) {
System.out.println("插入成工");
}
System.out.println(user);
// 插入要提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void testUpdate() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(5);
user.setName("yaco");
user.setPwd("123456");
int res = userDao.update(user);
if(res > 0) {
System.out.println("更新成功");
}
System.out.println(user);
// 插入要提交事务
sqlSession.commit();
sqlSession.close();
}
@Test
public void testDelete() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
userDao.deleteById(5);
sqlSession.commit();
sqlSession.close();
}
@Test
public void testMap() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
Map map = new HashMap();
map.put("name", "张三");
map.put("pwd","123456");
User user = userDao.findByNameAnsPwd(map);
System.out.println(user);
sqlSession.close();
}
@Test
public void testLike() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
List users = userDao.findUserLike("%李%");
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
}
三、使用Mybatis实现多对一查询
1、搭建数据表结构
创建两张表,分别式学生表和老师表,一个学生对应一个老师,一个老师可以对应多名学生。
CREATE TABLE student(
id INT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(30) DEFAULT NULL
tid INT(20) DEFAULT NULL,
CONSTRAINT FOREIGN KEY(tid) REFERENCES teacher(id)
)ENGINE = INNODB DEFAULT CHARSET utf8
CREATE TABLE teacher(
id INT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(20),
)ENGINE = INNODB DEFAULT CHARSET utf8
添加一些数据
2、搭建实体类及映射环境
- 实体类
public class Student {
private int id;
private String name;
private Teacher teacher;
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 Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", teacher=" + teacher +
'}';
}
}
public class Teacher {
private int id;
private String name;
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;
}
@Override
public String toString() {
return "Teacher{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
- StudentMapper持久层接口,查询学生,实现多对一的功能
public interface StudentMapper {
List selectStudentList();
List selectStudentList2();
Teacher selectTeacherById(int id);
}
3、使用嵌套查询完成多对一查询
4、使用子查询完成多对一查询
5、测试
public class MybatisTest {
@Test
public void test() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List students = mapper.selectStudentList();
for (Student student : students) {
System.out.println(student);
}
sqlSession.close();
}
@Test
public void test2() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List students = mapper.selectStudentList2();
for (Student student : students) {
System.out.println(student);
}
sqlSession.close();
}
}
测试输出
// 嵌套查询结果
Student{id=1, name='小明', teacher=Teacher{id=1, name='数学老师'}}
Student{id=2, name='小红', teacher=Teacher{id=2, name='语文老师'}}
Student{id=3, name='小兰', teacher=Teacher{id=3, name='英语老师'}}
Student{id=4, name='小宋', teacher=Teacher{id=1, name='数学老师'}}
Student{id=5, name='小丽', teacher=Teacher{id=2, name='语文老师'}}
Student{id=6, name='小叮', teacher=Teacher{id=3, name='英语老师'}}
// 子查询结果
Student{id=1, name='小明', teacher=Teacher{id=1, name='数学老师'}}
Student{id=2, name='小红', teacher=Teacher{id=2, name='语文老师'}}
Student{id=3, name='小兰', teacher=Teacher{id=3, name='英语老师'}}
Student{id=4, name='小宋', teacher=Teacher{id=1, name='数学老师'}}
Student{id=5, name='小丽', teacher=Teacher{id=2, name='语文老师'}}
Student{id=6, name='小叮', teacher=Teacher{id=3, name='英语老师'}}
四、使用Mybatis实现一对多查询
1、搭建实体类及映射环境
在上面多对一的情况下,学生实体类中有一个对应得老师实体引用,一对多得情况,老师实体类也要有一个学生得引用,因为是一对多得关系,这里用List存放学生集合
public class Student {
private int id;
private String name;
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;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
public class Teacher {
private int id;
private String name;
List students;
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 List getStudents() {
return students;
}
public void setStudents(List students) {
this.students = students;
}
@Override
public String toString() {
return "Teacher{" +
"id=" + id +
", name='" + name + '\'' +
", students=" + students +
'}';
}
}
- 创建持久层TeacherMapper接口
public interface TeacherMapper {
List selectTeacherById(@Param("tid") int tid);
}
2、使用嵌套查询完成一对多查询
3、测试
public class MybatisTest {
@Test
public void test() {
SqlSession sqlSession = MybatisUtil.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
List teachers = mapper.selectTeacherById(1);
for (Teacher teacher : teachers) {
System.out.println(teacher);
}
}
}
用例输出
Teacher{id=1, name='数学老师', students=[Student{id=1, name='小明'}, Student{id=4, name='小宋'}]}