文章目录
最近在学习瑞吉外卖,用到了MybatisPlus,之前没学过,特此做出学习笔记。
1. 数据库连接配置
在application.yml
中添加如下配置
spring:
application:
name: hmdp
#数据库配置信息
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/hmdianping?useSSL=false&serverTimezone=UTC
username: root
password: a123456789
# 设置连接池
hikari:
maximum-pool-size: 20
minimum-idle: 5
idle-timeout: 60000
2. Mybaits和MybatisPlus区别
- Mybatis是一个JDBC的升级版,使用Mybatis插件,Java语言可以通过XML的方式快速实现crud操作。本质上就是将Dao给封装起来的一个插件。
- MybatisPlus是Mybatis的升级版,在Mybatis的基础上提出了一些基础的接口和封装好的类,使得用户无需去编写简单的单表crud操作。
- Mybatis和MybatisPlus就相当于C和C++的区别,一般在开发的过程中我们直接使用MybatisPlus。
3. Mybatis使用
本博客的终点在于MybatisPlus,所以关于Mybatis就简单说一下如何配置。
3.1 MyBatis的安装
在IDEA
初始化SpringBoot时直接选择MyBatis
和MySQL
,会自动在pom.xml中安装依赖。
3.2 Mybatis的配置
在appication.properties
中进行简单的配置
- 连接数据库
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/数据库?useSSL=false&serverTimezone=UTC
username: 用户名
password: 密码
- 实现实体类属性名和数据库字段的映射(驼峰<->蛇形)
# mybatis增加驼峰命名转化(数据库变量名为标准蛇形命名,Java中变量名为标准的驼峰命名)
mybatis:
configuration:
map-underscore-to-camel-case: true
- 开启Mybatis的日志
#开启mybatis日志
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- 新建
Mapper
接口
被@Mapper
注释会直接生成一个可以访问数据库的Bean
对象
@Mapper
public interface UserMapper{
public List<User> selectById(Integer id);
}
- 使用XML实现Mybatis的操作
一个接口对应一个XML- 在resource文件夹下创建一个和java文件夹下mapper文件相同层级的目录
com/example/demo/mapper
- 在
mapper
中创建一个名字和待映射类名相同的xml文件UserMapper.xml
- 编写XML文件,XML的头部是固定的,需要注意的是
<mapper>
中的内容
- 在resource文件夹下创建一个和java文件夹下mapper文件相同层级的目录
<?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">
//namespace指定需要映射的接口
<mapper namespace="com.example.demo2.mapper.UserMapper">
//id指定方法名
//resultType指定返回值类型
<select id="selectById" resultType="com.example.demo2.Instance.User">
select * from user where id=#{id}
</select>
</mapper>
Service
中使用
public class UserServiceImpl implements UserService{
@AutoWired
UserMapper userMapper;
public List<User> getUserById(Integer id){
return userMapper.selectById(id);
}
}
3.3 Mybatis的注解
@Mapper
表明当前的接口是个Mapper,只有Mybatis
3.4 总结
- 安装
Mybatis
和MySql
的依赖 - 在
application.yml
中配置数据库连接 - 在
application.yml
中配置mybatis
的包扫描路径 - 在入口添加
MapperScan("com.example.demo.mapper")
- 编写
Mapper
接口并使用@Mapper
注释标注 - 在
resource
目录下新建mapper
文件夹,编写xml
- 通过
AutoWired
正常使用mapper - 安装
MybatisX
插件
4. MybatisPlus
MybatisPlus可以看作是一个高级版的Mybatis,我们重点查询如何使用MybatisPlus
4.1 安装依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
一般建议mybatis
和mybatis-plus
不要同时安装,因为可能存在版本冲突的问题。
4.2 Mybaits-Plus的配置
- 连接数据库
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/数据库?useSSL=false&serverTimezone=UTC
username: 用户名
password: 密码
- 基本配置
mybatis-plus:
#mapper配置文件
mapper-locations: classpath:mapper/*.xml
type-aliases-package: 实体类包的地址
configuration:
#开启驼峰命名
map-underscore-to-camel-case: true
global-config:
db-config:
id-type: auto
4.3 使用过程
- 配置
mapper
与mybatisplus
不一样的是interface
需要继承BaseMapper
这个接口,这样才能使用MybatisPlus
自带的接口。建议添加上@Mapper
,因为这样我们就能想使用Mybatis
一样使用mapper
。
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
- 配置
Service
接口
IService
里面是Service
接口自带的实现类。
public interface UserService extends IService<User> {
List<User> listUser(String name,Integer status,Integer minBalance,Integer maxBalance);
}
- 配置
Service
的实现类
可以使用mybatis-plus
自带的语法实现增删改查。
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Override
public List<User> listUser(String name,Integer status,Integer minBalance,Integer maxBalance){
List<User> users = lambdaQuery().like(User::getUsername, name)
.eq(User::getStatus, status)
.between(User::getBalance, minBalance, maxBalance).list();
return users;
}
}
4.4 Mybatis-plus常用操作
- 查询
# 使用lambda语法
List<User> users = lambdaQuery().like(User::getUsername, name)
.eq(User::getStatus, status)
.between(User::getBalance, minBalance, maxBalance).list();
# 使用QueryWrapper条件构造器
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name", "John"); // 等价于 WHERE name = 'John'
List<User> users = userMapper.selectList(queryWrapper);
- 分页
# MybatisPlus自带分页的功能,实现起来非常方便
Page<User> pages=this.query().page(current,page_size);
List<User> users=pages.getRecords();
4.5 常用注解
@Mapper
用于注解Mapper接口@TableId(value = "id", type = IdType.AUTO)必选
指定数据表的主键@TableName必选
非常重要,用于绑定实体类和数据表,下面将Blog
实体类与tb_blog
绑定,字段值一一对应。
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_blog")
public class Blog implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 商户id
*/
private Long shopId;
/**
* 用户id
*/
private Long userId;
/**
* 用户图标
*/
@TableField(exist = false)
private String icon;
/**
* 用户姓名
*/
@TableField(exist = false)
private String name;
/**
* 是否点赞过了
*/
@TableField(exist = false)
private Boolean isLike;
}
@TableField(exist=False)
表明实体类中该字段不存在于数据表中,两者没有对应关系。
4.6 总结
- 安装
MybatisPlus
和MySql
的依赖 - 在
application.yml
中配置数据库连接 - 在
application.yml
中配置mybatis-plus
的包扫描路径 - 在入口添加
MapperScan("com.example.demo.mapper")
- 编写
Mapper
接口并使用@Mapper
注释标注 - 在
resource
目录下新建mapper
文件夹,编写xml
- 通过
AutoWired
正常使用mapper - 安装
MybatisX
插件
5. 使用过程中的疑问?
- 如果
select
语句只返回表中的某些字段的值,我们要怎么办,还能把数据封装到实体类中吗?- 我们可以使用HashMap存储返回结果,之后再在Service中处理。
<!-- 返回类型 --> <resultMap id="testRestMap" type="java.util.HashMap"> <result column="province_name" jdbcType="VARCHAR" property="provinceName" /> <result column="area_name" jdbcType="VARCHAR" property="areaName" /> <result column="lane_num" jdbcType="VARCHAR" property="laneNum" /> <result column="road_name" jdbcType="VARCHAR" property="roadName" /> </resultMap> <!--sql查询 --> <select id="selTest" resultMap="testRestMap"> select province_name, area_name,lane_num, road_name from site_info where 1=1 and del_flag='0' </select>
- 新建一个实体类,之后再XML中自定义映射规则,但这种方法很笨拙,不建议使用。
<!-- 全省设备数量统计 数据返回 --> <resultMap id="DeviceNumber" type="com.sinosoft.pojo.DeviceNumber"> <result column="distCode" jdbcType="VARCHAR" property="distCode" /> <result column="distName" jdbcType="VARCHAR" property="distName" /> <result column="number" jdbcType="VARCHAR" property="number" /> </resultMap> <!-- 全省设备数量统计 --> <select id="statisticsDevice" resultMap="DeviceNumber"> SELECT t1.distCode, t1.distName, t2.number FROM ( select fd_objectid distCode, area_name distName FROM t_sys_area WHERE LEVEL='2' ) t1 LEFT JOIN ( SELECT city_no, count(*) as number FROM site_info WHERE 1=1 and del_flag='0' and is_bridge!='1' GROUP BY city_no )t2 on t2.city_no=t1.distCode </select>
-
如果出现
Bing error
相关错误要如何解决?
我其实也不知道怎么解决,查了网上方法都没有解决我的问题,项目还是会出现这个问题,但是我从0新建项目又不会出现这个错误,我合理怀疑是版本号冲突之类地问题。- 查询
XML
的namespace
是否正确 - 查询
application.yml
中是否正确配置了mapper
的包扫描路径 - 查询入口文件是否配置了
MapperScan
- 查询是否同时使用
Mybatis
和MybatisPlus
,这可能会导致依赖冲突 - 检查一下
Mapper
中的自定义函数在xml
中是否实现了
如果上面的方法都没法解决,那我是真不知道了
- 查询