欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > SpringBoot中的数据库查询及Mybatis和MybatisPlus的使用

SpringBoot中的数据库查询及Mybatis和MybatisPlus的使用

2025/4/27 16:45:08 来源:https://blog.csdn.net/qq_33880925/article/details/134002331  浏览:    关键词:SpringBoot中的数据库查询及Mybatis和MybatisPlus的使用

文章目录

    • 1. 数据库连接配置
    • 2. Mybaits和MybatisPlus区别
    • 3. Mybatis使用
      • 3.1 MyBatis的安装
      • 3.2 Mybatis的配置
      • 3.3 Mybatis的注解
      • 3.4 总结
    • 4. MybatisPlus
      • 4.1 安装依赖
      • 4.2 Mybaits-Plus的配置
      • 4.3 使用过程
      • 4.4 Mybatis-plus常用操作
      • 4.5 常用注解
      • 4.6 总结
    • 5. 使用过程中的疑问?

最近在学习瑞吉外卖,用到了MybatisPlus,之前没学过,特此做出学习笔记。

1. 数据库连接配置

application.yml中添加如下配置

spring:application:name: hmdp#数据库配置信息datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/hmdianping?useSSL=false&serverTimezone=UTCusername: rootpassword: a123456789# 设置连接池hikari:maximum-pool-size: 20minimum-idle: 5idle-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时直接选择MyBatisMySQL,会自动在pom.xml中安装依赖。

3.2 Mybatis的配置

appication.properties中进行简单的配置

  • 连接数据库
spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/数据库?useSSL=false&serverTimezone=UTCusername: 用户名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
    1. 在resource文件夹下创建一个和java文件夹下mapper文件相同层级的目录com/example/demo/mapper
    2. mapper中创建一个名字和待映射类名相同的xml文件UserMapper.xml
    3. 编写XML文件,XML的头部是固定的,需要注意的是<mapper>中的内容
	<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//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{@AutoWiredUserMapper userMapper;public List<User> getUserById(Integer id){return userMapper.selectById(id);}
}

3.3 Mybatis的注解

  • @Mapper
    表明当前的接口是个Mapper,只有Mybatis

3.4 总结

  1. 安装MybatisMySql的依赖
  2. application.yml中配置数据库连接
  3. application.yml中配置mybatis的包扫描路径
  4. 在入口添加MapperScan("com.example.demo.mapper")
  5. 编写Mapper接口并使用@Mapper注释标注
  6. resource目录下新建mapper文件夹,编写xml
  7. 通过AutoWired正常使用mapper
  8. 安装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>

一般建议mybatismybatis-plus不要同时安装,因为可能存在版本冲突的问题。

4.2 Mybaits-Plus的配置

  • 连接数据库
spring:datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/数据库?useSSL=false&serverTimezone=UTCusername: 用户名password: 密码
  • 基本配置
mybatis-plus:#mapper配置文件mapper-locations: classpath:mapper/*.xmltype-aliases-package: 实体类包的地址configuration:#开启驼峰命名map-underscore-to-camel-case: trueglobal-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 {@Overridepublic 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);

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(eexist=False)
    表明实体类中该字段不存在于数据表中,两者没有对应关系。

4.6 总结

  1. 安装MybatisPlusMySql的依赖
  2. application.yml中配置数据库连接
  3. application.yml中配置mybatis-plus的包扫描路径
  4. 在入口添加MapperScan("com.example.demo.mapper")
  5. 编写Mapper接口并使用@Mapper注释标注
  6. resource目录下新建mapper文件夹,编写xml
  7. 通过AutoWired正常使用mapper
  8. 安装MybatisX插件

5. 使用过程中的疑问?

  1. 如果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_infowhere 1=1and 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">SELECTt1.distCode,t1.distName,t2.numberFROM(select fd_objectid distCode,area_name  distNameFROM t_sys_area WHERE LEVEL='2') t1 LEFT JOIN (SELECT city_no,count(*) as number FROM site_info WHERE 1=1and del_flag='0'and is_bridge!='1'GROUP BY city_no)t2 on t2.city_no=t1.distCode
    </select>
    
    1. 如果出现Bing error相关错误要如何解决?
      我其实也不知道怎么解决,查了网上方法都没有解决我的问题,项目还是会出现这个问题,但是我从0新建项目又不会出现这个错误,我合理怀疑是版本号冲突之类地问题。

      • 查询XMLnamespace是否正确
      • 查询application.yml中是否正确配置了mapper的包扫描路径
      • 查询入口文件是否配置了MapperScan
      • 查询是否同时使用MybatisMybatisPlus,这可能会导致依赖冲突
      • 检查一下Mapper中的自定义函数在xml中是否实现了

      如果上面的方法都没法解决,那我是真不知道了

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词