前言:

本文内容:注解增删改查、Lombok使用、复杂查询环境搭建

推荐免费MyBatis基础教程视频:【狂神说Java】Mybatis最新完整教程IDEA版通俗易懂_哔哩哔哩_bilibili

注解增删改查

我们可以在工具类创建的时候实现自动提交事务

MybatisUtil.java

1
2
3
4
5
// .......  
// 设置为true自动提交事务
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}

关于@Param()注解

  • 基本类型的参数或者String类型,需要加
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略(建议都加上)
  • 在SQL中引用的就是@Param("value")里的value

#{},${}的区别:${}会存在SQL注入,而#{}不会

使用注解实现CRUD

UserMapper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
// 使用注解实现CRUD
// 查询 参数需要@Param("value") 以这个为主
@Select("select * from user where id=#{id}")
User getUserById(@Param("id") int id, @Param("name") String name);
// 添加 引用对象不需要@Param 这里写实体类里的
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
int addUser(User user);
// 修改
@Update("update user set name=#{name},pwd=#{pwd} where id=#{id}")
int updateUser(User user);
// 删除
@Delete("delete from user where id=#{id}")
int deleteUser(@Param("id") int id);

MapperTest.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// id查询
@Test
public void getUserById(){
// 获得sqlSession对象
SqlSession sqlSession = MyBatisUtil.getSqlSession();
// 执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// mapper调用查询方法
User user = mapper.getUserById(1,"admin");
// 输出查询结果
System.out.println(user);
// 关闭sqlSession
sqlSession.close();
}
// 添加
@Test
public void addUser(){
// 获得sqlSession对象
SqlSession sqlSession = MyBatisUtil.getSqlSession();
// 执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// mapper调用添加方法
mapper.addUser(new User(5, "小呆呆", "123123"));
// 关闭sqlSession
sqlSession.close();
}
// 修改
@Test
public void updateUser(){
// 获得sqlSession对象
SqlSession sqlSession = MyBatisUtil.getSqlSession();
// 执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// mapper调用修改方法
mapper.updateUser(new User(5, "小呆瓜", "33333"));
// 关闭sqlSession
sqlSession.close();
}
// 删除
@Test
public void deleteUser(){
// 获得sqlSession对象
SqlSession sqlSession = MyBatisUtil.getSqlSession();
// 执行sql
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// mapper调用删除方法
mapper.deleteUser(6);
// 关闭sqlSession
sqlSession.close();
}

运行结果

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
===================ID查询=====================
Opening JDBC Connection
Created connection 592617454.
==> Preparing: select * from user where id=?
==> Parameters: 1(Integer)
<== Columns: id, name, pwd
<== Row: 1, admin, 123
<== Total: 1
User{id=1, name='admin', pwd='123'}
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@23529fee]
Returned connection 592617454 to pool.

Process finished with exit code 0

===================添加=====================
Opening JDBC Connection
Created connection 487075464.
==> Preparing: insert into user(id,name,pwd) values(?,?,?)
==> Parameters: 5(Integer), 小呆呆(String), 123123(String)
<== Updates: 1
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1d082e88]
Returned connection 487075464 to pool.

Process finished with exit code 0
===================修改=====================
Opening JDBC Connection
Created connection 6320204.
==> Preparing: update user set name=?,pwd=? where id=?
==> Parameters: 小呆瓜(String), 33333(String), 5(Integer)
<== Updates: 1
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@60704c]
Returned connection 6320204 to pool.

Process finished with exit code 0
===================删除=====================
Opening JDBC Connection
Created connection 112302969.
==> Preparing: delete from user where id=?
==> Parameters: 6(Integer)
<== Updates: 1
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6b19b79]
Returned connection 112302969 to pool.

Process finished with exit code 0

Lombok的使用

官方简介

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

ProjectLombok是一个java库,可以自动插入到编辑器和构建工具中,提高java的性能。
永远不要再编写另一个getter或equals方法,使用一个注释,你的类就有了一个功能齐全的生成器,自动化了你的日志变量,等等。

官方地址:Project Lombok

通过下载安装lombok.jar或者引入Maven即可使用

1
2
3
4
5
6
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>

简单使用

通过IDEA安装Lombok插件(新版IDEA默认安装Lombok插件)

File->Settings-Plugins->搜索Lombok安装即可

在Pom.xml导入jar包

1
2
3
4
5
6
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>

如果导入异常,可以

File->Settings->Build, Execution, Deployment->Compiler->Annotation Processors->勾选Enable annotation processing

常用参数

1
2
3
4
5
6
@Getter and @Setter
@ToString
@EqualsAndHashCode
@AllArgsConstructor:有参构造@NoArgsConstructor:无参构造
@Data:无参构造,get,set,toString,hashCode,equals
@Accessors

pojo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.jokerdig.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;

/**
* 实体类
* @author Joker大雄
* @data 2022/4/23 - 15:22
**/
// @Data可以帮我们实现get、set、toString、hashCode、无参构造
// @AllArgsConstructor 有参构造
@Data
@AllArgsConstructor
public class User implements Serializable {
private int id;
private String name;
private String pwd;

}

优点及缺点

优点:

  • 通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,提高了一定开发效率
  • 让代码变得简洁,不用过多的去关注相应的方法
  • 属性做修改时,也简化了维护为这些属性所生成的getter/setter方法等

缺点:

  • 不支持多种参数构造器的重载
  • 虽省去了手动创建getter/setter方法,但降低了源代码的可读性和完整性,阅读源码也不舒适

复杂查询环境搭建

一对多

  • 对于老师而言,集合… 一个老师有很多学生

多对一

  • 对于学生而言,关联… 多个学生,关联一个老师

搭建测试环境

创建老师和学生表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `teacher`(`id`, `name`) VALUES (1, '张三老师');

CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');

父项目pom.xml添加

1
2
3
4
5
6
<!--        lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>

mybatis-config.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
34
35
36
37
38
39
40
<?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>
<!-- 引入db.properties-->
<!-- 也可以在标签里传值,但优先使用外部配置-->
<properties resource="db.properties"/>
<!-- 配置日志工厂-->
<settings>
<!-- 标准日志工厂-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- log4j 不推荐使用-->
<!-- <setting name="logImpl" value="LOG4j"/>-->
</settings>


<!-- 配置别名 一-->
<typeAliases>
<typeAlias type="com.jokerdig.pojo.Teacher" alias="Teacher"/>
<typeAlias type="com.jokerdig.pojo.Student" alias="Student"/>
</typeAliases>
<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="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- 绑定接口-->
<mappers>
<mapper resource="com/jokerdig/mapper/TeacherMapper.xml"/>
<mapper resource="com/jokerdig/mapper/StudentMapper.xml"/>
</mappers>
</configuration>

项目结构

82

测试简单查询

1
2
3
4
5
6
7
8
9
10
11
Opening JDBC Connection
Created connection 597190999.
==> Preparing: select * from teacher
==> Parameters:
<== Columns: id, name
<== Row: 1, 张三老师
<== Total: 1
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@23986957]
Returned connection 597190999 to pool.

Process finished with exit code 0