其实对我个人而言还是不够熟悉JPA、hibernate,所以觉得这两种框架使用起来好麻烦啊。

一直用的Mybatis作为持久层框架,

JPA(Hibernate)主张所有的SQL都用Java代码生成,

而Mybatis则更主张用原生SQL。

准备

#引入依赖

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>

配置参数

修改application.yml:

spring:
datasource:
url: jdbc:mysql://localhost:3306/database_name?characterEncoding=utf-8//有的电脑需要加入时区参数zone不然会报错
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver

初始化数据库

-- create database springboot_mybatis charset utf8;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`username` varchar(255) DEFAULT NULL COMMENT '用户名',
`password` varchar(255) DEFAULT NULL COMMENT '密码',
`create_time` datetime DEFAULT NULL COMMENT '创建日期',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

注解版

Mybatis提供了一些注解实现快速CRUD,比如:@Select,@Update,@Insert,@Delete

相信你在看这篇文章之前已经用过Mybatis了(比如之前的SSM开发),

所以呢,使用注解方式按照XML方式的SQL写法就好。

写在前面之前在SSM开发时,

会在MapperScannerConfigurer中配置:

<property name="basePackage" value="xxx.mapper"/>用于使用Mybatis的接口代理开发模式(且接口和XML需要名称相同)。

那么在SpringBoot整合Mybatis中也要有对应的配置:

方式一:在每个interface Mapper前添加@Mapper注解

方式二:在Application.java启动类前添加@MapperScan("mapper所在的包名")注解

增删改查操作如下:

创建Entity /entity/User.java

@Data
@ToString
public class User implements Serializable {
private Long id;
private String username;
private String password;
private Date createTime;
//用lombok插件注解不用再写getter和setter
}
创建interface /mapper/UserMapperAno.java
public interface UserMapperAno {

    @Select("select * from user")
@Results({
@Result(property = "createTime", column = "create_time")
})
List<User> findAll(); @Select("select * from user where id = #{id}")
@Results({
@Result(property = "createTime", column = "create_time")
})
User findById(Long id); @Insert("insert into user(username,password,create_time) values(#{username},#{password},#{createTime})")
void save(User user); @Update("update user set username=#{username},password=#{password} where id=#{id}")
void update(User user); @Delete("delete from user where id=#{id}")
void delete(Long id);
}

其中@Result注解用于修饰返回结果集,若Entity和数据表字段不一致可以用其修饰

测试

创建测试类 /mapper/UserMapperAnoTest.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
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserMapperAnoTest {
private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private UserMapper userMapper; @Test
public void testFindAll() {
List<User> list = userMapper.findAll();
list.forEach(user -> {
logger.info("user={}", user);
});
} @Test
public void testFindById(){
logger.info("user={}", userMapper.findById(1L));
} @Test
public void testSave(){
User user = new User();
user.setUsername("测试");
user.setPassword("123");
user.setCreateTime(new Date());
userMapper.save(user);
testFindAll();
} @Test
public void testUpdate() {
User user = new User();
user.setId(4L);
user.setUsername("测试呀");
userMapper.update(user);
testFindAll();
} @Test
public void delete() {
userMapper.delete(3L);
testFindAll();
}
}

小结

以上是常用CRUD操作的Mybatis注解版实现,对于基本的操作,使用注解确实比传统的XML简单好多,虽然也是SQL写在注解中,但是感觉比JPA的方式要简便一些(个人理解)。

XML版

使用Mybatis的XML开发方式应该是我们比较熟悉的,和注解版最大的不同就是Dao层,XML版会自动根据Dao层接口的方法名自动映射到XML中同名id对应的SQL。

修改application.yml

添加如下Mybatis配置属性

1
2
3
4
5
6
7
8
9
#mybatis配置
mybatis:
mapper-locations: classpath:mapper/**/*.xml
type-aliases-package: cn.tycoding.entity
configuration:
# 使用jdbc的getGeneratedKeys 可以获取数据库自增主键值
use-generated-keys: true
# 开启驼峰命名转换,如:Table(create_time) -> Entity(createTime)。不需要我们关心怎么进行字段匹配,mybatis会自动识别`大写字母与下划线`
map-underscore-to-camel-case: true

CRUD

创建interface UserMapperXML.java

1
2
3
4
5
6
7
8
9
10
11
12
public interface UserMapperXML {

    List<User> findAll();

    User findById(Long id);

    void save(User user);

    void update(User user);

    void delete(Long id);
}

resources/下创建/mapper/UserMapperXML.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
<?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="cn.tycoding.mapper.UserMapperXML"> <select id="findAll" resultType="cn.tycoding.entity.User">
select * from user
</select> <select id="findById" resultType="cn.tycoding.entity.User">
select * from user where id = #{id}
</select> <insert id="save" parameterType="cn.tycoding.entity.User">
insert into user(username,password,create_time) values(#{username},#{password},#{createTime}
</insert> <update id="update" parameterType="cn.tycoding.entity.User">
update user set username=#{username},password=#{password} where id=#{id}
</update> <delete id="delete" parameterType="long">
delete from user where id=#{id}
</delete> </mapper>

测试

创建测试类UserMapperXMLTest.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
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserMapperXMLTest {
private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private UserMapperXML userMapperXML; @Test
public void testFindAll() {
List<User> list = userMapperXML.findAll();
list.forEach(user -> {
logger.info("user={}", user);
});
} @Test
public void testFindById(){
logger.info("user={}", userMapperXML.findById(1L));
} @Test
public void testSave(){
User user = new User();
user.setUsername("测试");
user.setPassword("123");
user.setCreateTime(new Date());
userMapperXML.save(user);
testFindAll();
} @Test
public void testUpdate() {
User user = new User();
user.setId(4L);
user.setUsername("测试呀");
userMapperXML.update(user);
testFindAll();
} @Test
public void delete() {
userMapperXML.delete(3L);
testFindAll();
}
}

小结

练习了Mybatis注解版和XML版开发模式,更觉得两者配合使用最好,

简单的CRUD操作使用注解完全可以实现;

复杂的查询,比如Mybatis的动态SQL特性在注解中应该很难体现,而在XML中就很容易实现了。

Spring Boot整合Mybatis(注解方式和XML方式)的更多相关文章

  1. Spring Boot整合MyBatis(非注解版)

    Spring Boot整合MyBatis(非注解版),开发时采用的时IDEA,JDK1.8 直接上图: 文件夹不存在,创建一个新的路径文件夹 创建完成目录结构如下: 本人第一步习惯先把需要的包结构创建 ...

  2. Spring Boot整合Mybatis完成级联一对多CRUD操作

    在关系型数据库中,随处可见表之间的连接,对级联的表进行增删改查也是程序员必备的基础技能.关于Spring Boot整合Mybatis在之前已经详细写过,不熟悉的可以回顾Spring Boot整合Myb ...

  3. Spring Boot系列(三):Spring Boot整合Mybatis源码解析

    一.Mybatis回顾 1.MyBatis介绍 Mybatis是一个半ORM框架,它使用简单的 XML 或注解用于配置和原始映射,将接口和Java的POJOs(普通的Java 对象)映射成数据库中的记 ...

  4. Spring Boot整合Mybatis并完成CRUD操作

    MyBatis 是一款优秀的持久层框架,被各大互联网公司使用,本文使用Spring Boot整合Mybatis,并完成CRUD操作. 为什么要使用Mybatis?我们需要掌握Mybatis吗? 说的官 ...

  5. spring boot 整合 mybatis 以及原理

    同上一篇文章一样,spring boot 整合 mybatis过程中没有看见SqlSessionFactory,sqlsession(sqlsessionTemplate),就连在spring框架整合 ...

  6. Spring Boot 整合mybatis时遇到的mapper接口不能注入的问题

    现实情况是这样的,因为在练习spring boot整合mybatis,所以自己新建了个项目做测试,可是在idea里面mapper接口注入报错,后来百度查询了下,把idea的注入等级设置为了warnin ...

  7. 太妙了!Spring boot 整合 Mybatis Druid,还能配置监控?

    Spring boot 整合 Mybatis Druid并配置监控 添加依赖 <!--druid--> <dependency> <groupId>com.alib ...

  8. Spring Boot整合Mybatis报错InstantiationException: tk.mybatis.mapper.provider.base.BaseSelectProvider

    Spring Boot整合Mybatis时一直报错 后来发现原来主配置类上的MapperScan导错了包 由于我使用了通用Mapper,所以应该导入通用mapper这个包

  9. 【spring boot】14.spring boot集成mybatis,注解方式OR映射文件方式AND pagehelper分页插件【Mybatis】pagehelper分页插件分页查询无效解决方法

    spring boot集成mybatis,集成使用mybatis拖沓了好久,今天终于可以补起来了. 本篇源码中,同时使用了Spring data JPA 和 Mybatis两种方式. 在使用的过程中一 ...

随机推荐

  1. springboot 框架 - 探究-pom文件

    一.pom文件 父项目 <parent> <groupId>org.springframework.boot</groupId> <artifactId> ...

  2. ubuntu 安装 gd

    最近装一套系统,提示没开启GD, 1.首先检查一下,是否安装 新建一个文件 <?php phpinfo(); ?> 如果安装了,会在页面显示 2.没安装当然没有了 这个安装也是根据php版 ...

  3. AngularJS Learning Notes

    AngularJS 简介 AngularJS 是一个 JavaScript 框架.它可通过 <script> 标签添加到 HTML 页面. AngularJS 通过 指令 扩展了 HTML ...

  4. pthon中的基本运算

    格式化输出的三种方式 1.占位符 程序中经常会有这样的场景:要求用户输入信息,然后打印成固定的格式 比如要求用户输入用户名和年龄,然后打印如下格式: my name is xxx,my age is ...

  5. 洛谷P1734 最大约数和(01背包)

    题目描述 选取和不超过S的若干个不同的正整数,使得所有数的约数(不含它本身)之和最大. 输入格式 输入一个正整数S. 输出格式 输出最大的约数之和. 输入输出样例 输入 #1 11 输出 #1 9 说 ...

  6. 在HTML中实现两个div并排显示

    在HTML中让两个div并排显示,通常情况下有三种实现方式,包括: (1)设置为行内样式,display:inline-block (2)设置float浮动 (3)设置position定位属性为abs ...

  7. python练习:斐波那契数列的递归实现

    python练习:斐波那契数列的递归实现 重难点:递归的是实现 def fib(n): if n==0 or n==1: return 1 else: return fib(n-1)+fib(n-2) ...

  8. 基于G6画个xmind出来

    公司产品因为业务发展,出现了一个新的需求:需要去实现知识库的层级知识展示,展示效果通过树图来实现,具体的展示形式可见下图: 其中有几个需要注意点: 节点上的详情icon可以点击,点击展开关闭详情 节点 ...

  9. 拓扑排序板子 hihocoder-1174

    思路 不断删入度为1的点及其出边. 图解 #include <bits/stdc++.h> using namespace std; const int maxn=1e5+10; vect ...

  10. hdu1698 区间更新

    初写线段树的时候,印象最深的一道,有一个pushdown的操作,使我的tle变成了ac 题意 输入t,然后t组数据 输入n,m,n代表n个点上价值全是1的绳子,m代表m次操作 m行l,r,val  就 ...