Mybatis-Plus操作数据库
目录
Mybatis-Plus操作数据库
目录
一、使用mybatis-Plus前期准备
创建 springboot工程
首先下载一个lombok插件,使实体类可以使用@data不用set和get
增加依赖
<!--spring连接数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--spring整合mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
yml配置文件
spring:
application:
name: tqw-item
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
username: root
password: root
#配置mybatis
mybatis-plus:
#别名包,实体类的路径
type-aliases-package: com.example.demo.pojo
#将所有的映射文件全部加载
mapper-locations: classpath:/mappers/*.xml
#开启驼峰映射
configuration:
map-underscore-to-camel-case: true
创建实体类
package com.example.demo.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@Accessors(chain = true)
@TableName("user") //关联的数据库表
public class User implements Serializable {
@TableId(type = IdType.AUTO) //id自增
private Integer id;
private String name;
private String pwd;
private Integer age;
}
创建mapper层接口
package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
使用注解在service层或测试类注入mapper接口
@Autowired
private UserMapper userMapper;
二、使用mybatis-Plus分装方法
注意事项: 只适合单表操作
实体类初始化数据,或从前端获取。新增和修改数据库需要使用
User userTable=new User();
user.setId(5);
user.setName("admin");
user.setPwd("123456");
1.1、根据id进行增删改查
//根据id查询、删除数据库数据
User user = userMapper.selectById(1); //查询单条数据
userMapper.deleteById(5); //删除单条数据
List<User> lists = userMapper.selectBatchIds(1,2); //根据id集合查询多条数据
userMapper.deleteBatchIds(1,2); //根据id集合删除多条数据
userMapper.insert(user); //根据实体类id增加一条数据,id自增情况下实体类id的值无效,按自增增加
userMapper.updateById(userTable); //根据实体类id修改一条数据
1.2、根据条件构造器进行删除、修改、查询
创建条件构造器
//创建条件构造器
LambdaQueryWrapper<UserTable> queryWrapper=new LambdaQueryWrapper<>();
//填充条件
queryWrapper.eq(User::getName, "条件值"); //相当于where条件 name='条件值'
queryWrapper.between(User::getName, "区间一", "区间二");//范围内查询between
queryWrapper.like(User::getName, "模糊查询的字符"); //模糊查询like name like %模糊查询的字符%
queryWrapper.like(true,User::getUName, "李");//true表示进行模糊查询,false表示取消模糊查询
queryWrapper.eq(UserTable::getUName, "李四").or() //or()表示where条件或者
.le(UserTable::getUCode, 2);
queryWrapper.groupBy(User::getName); //相当于group by分组
queryWrapper.in(User::getName, "包括的值','分割,或者list、set集合"); //相当于in
queryWrapper.orderByAsc(User::getName); //升序
queryWrapper.orderByDesc(User::getName);//降序
queryWrapper.ge(User::getName, "要比较的值"); //大于等于
queryWrapper.le(User::getName, "要比较的值"); //小于等于
queryWrapper.clear(); //清除之前上面填充的条件
queryWrapper.eq(User::getName, "王五");
通过条件构造器进行删除、修改、查询
List<User> listse = userMapper.selectList(queryWrapper); //根据条件查询多条数据
userMapper.delete(queryWrapper); //根据条件删除数据
userMapper.update(user, queryWrapper); //根据条件修改数据为第一个参数实体
三、mybatis-Plus使用注解进行数据库操作
在mapper层接口进行操作
package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper extends BaseMapper<User> {
// @Update("") //修改注解
// @Delete("") //删除注解
// @Insert("") //新增注解
//查询注解
@Select("select * from user where name=#{name} and pwd=#{pwd}")
User find(String name, String pwd);
}
四、mybatis-Plus使用XML文件对数据库进行操作
1、单表操作
mapper接口创建方法
package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
User findAll(User user);
//传list集合参数
List<User> findInArray(List<Integer> list);
//只能有一个参数,如果有多个参数,则需要封装为单值Map
//@Param将参数封装为Map集合
//传两个数组,通过注解封装成map集合
List<User> findInMap(@Param("ids1") Integer[] ids1,
@Param("ids2") Integer[] ids2);
List<User> findSqlWhere(User user);
void updateUser(User user);
List<User> findChoose(User user);
}
1.1、普通传参操作
创建 .xml 文件,创建路径与配置文件映射路径一致
主要: 如果开启驼峰命名符合驼峰命名的可以不需要映射,不符合驼峰命名必须进行映射否则实体类与表字段对应不上
知识点1: 通过 #{参数名称/对象中的属性/Map中的key}
知识点2: xml文件中有些字符需要转义
:>;< :<;&:&
<?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是mybaits映射文件的唯一标识,与mapper接口对应-->
<mapper namespace="com.example.demo.mapper.UserMapper">
<!--标识使用二级缓存!!!,表信息不是只读的不进行缓存-->
<cache/>
<!--id指mapper接口的方法;resultType有返回值的实体类路径,
与配置别名路径相同可以省略只写类名,无返回值可以不写
resultType="User"返回的数据类型-->
<!--<select id="findAll" resultType="com.example.demo.pojo.User">-->
<select id="findAll" resultType="User">
<!--传实体类直接写属性名称-->
select * from user where name= #{name} and pwd=#{pwd}
</select>
<!--
属性说明: id="唯一标识,不能重复"
type="映射的POJO对象的类型"
简化说明: 如果字段名称与属性名称一致则可以省略
autoMapping="true" 开启自动映射
-->
<resultMap id="userRM" type="User" autoMapping="true">
<!--1.标识主键,column指表字段名 property指实体类属性名称-->
<id column="id" property="id"/>
<!--2.映射结果集,实体类与字段符合驼峰命名的可以不写-->
<result column="name" property="name"/>
<!--<result column="pwd" property="pwd"/>-->
<!--<result column="age" property="age"/>-->
</resultMap>
</mapper>
1.2、遍历数组集合的传参操作
<!--
需求: Integer[] ids 中的数据一个一个取出来.拼接Sql
知识点: mybatis中如何遍历数组
foreach标签用法:
1. collection:需要遍历的集合的类型
1.1 数组类型 关键字:array
1.2 list类型 关键字:list
1.3 map类型 关键字:Map中的key,单纯的map类型直接写key不需要遍历
2. open/close 循环开始和结束标签,一般自己写
3. item 遍历数据的变量名称
4. separator 参数之间的分隔符
-->
<select id="findInArray" resultType="User">
select * from demo_user where id in (
<foreach collection="list" item="id" separator=",">
#{id}
</foreach>
)
</select>
<!--参数传递是Map集合,所以关键字使用key-ids1 -->
<select id="findInMap" resultType="User">
select * from demo_user where id in (
<foreach collection="ids1" item="id" separator=",">
#{id}
</foreach>
,
<foreach collection="ids2" item="id" separator=",">
#{id}
</foreach>
)
1.3、传有空值或null值的参数或实体类
<!--
问题说明: 前端数据传递时可能会有null数据.
如果数据为null则不能充当where条件
解决方案: 动态Sql实现
语法:
<if test="判断条件"> id = #{id}</if>
true: 则拼接标签内容
false: 则不拼接标签内容
<where>标签: 去除where后边多余的and/or
-->
<select id="findSqlWhere" resultType="User">
select * from demo_user
<where>
<if test="id != null"> id = #{id}</if>
<if test="name !=null">and name = #{name}</if>
<if test="age !=null"> and age = #{age}</if>
<if test="sex !=null"> and sex = #{sex}</if>
</where>
</select>
<!--根据对象中不为null的属性 当做set条件
语法: set标签 去除多余1个,号
-->
<update id="updateUser">
update demo_user
<set>
<if test="name !=null">name=#{name},</if>
<if test="age !=null"> age=#{age},</if>
<if test="sex !=null"> sex=#{sex},</if>
</set>
where id = #{id}
</update>
<!--
* 如果name有值,则根据name查询.
* 如果name没有值,则根据age查询.
* 如果name/age都没有值,则根据sex查询
语法类似: if->else-if->else
-->
<select id="findChoose" resultType="User">
select * from demo_user
<where>
<choose>
<when test="name !=null"> name=#{name}</when>
<when test="age !=null"> age = #{age}</when>
<!--必须保证sex必须有值 -->
<otherwise>sex=#{sex}</otherwise>
</choose>
</where>
2、多表操作
2.1、数据一对一操作
创建一个一对一数据实体
package com.example.demo.pojo;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@Accessors(chain = true)
@TableName("emp") //关联的数据库表
public class Emp implements Serializable {
private Integer empId;
private String empName;
//一对一封装
private Dept dept; //deptId,deptName
}
创建mapper接口
package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface EmpMapper extends BaseMapper<Emp> {
List<Emp> findAll();
}
创建XML文件
<!--
知识点:
1.如果单表查询首选resultType
2.如果进行关联查询 首选resultMap
3.如果sql的结果集出现了重名字段,则mybatis映射必然报错.
-->
<select id="findAll" resultMap="empRM">
SELECT emp.*,dept.dept_name FROM emp,dept
WHERE emp.dept_id = dept.dept_id
</select>
<!-- 完成一对一封装
目的: 一个员工中封装一个部门对象
语法:
1.association 表示一对一封装
2.property 当前主对象的属性名称
3.javaType 指定属性的类型
-->
<resultMap id="empRM" type="Emp" autoMapping="true">
<!-- 标识主键信息 -->
<id column="emp_id" property="empId"/>
<!-- 其他属性符合驼峰命名省略 -->
<!--<result column="emp_name" property="empName"/>-->
<!--完成一对一映射-->
<association property="dept" javaType="Dept" autoMapping="true">
<!-- 标识主键信息 -->
<id column="dept_id" property="deptId"/>
<!-- 其余符合驼峰命名省略 -->
</association>
</resultMap>
2.2、数据一对多操作
创建一个一对多数据实体
package com.example.demo.pojo;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
@Data
@Accessors(chain = true)
@TableName("dept") //关联的数据库表
public class Dept implements Serializable {
private Integer deptId;
private String deptName;
//一对多封装
private List<Emp> emps;
}
创建mapper接口
package com.example.demo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface DeptMapper extends BaseMapper<Dept> {
List<Dept> findAll();
}
创建XML文件
<select id="findAll" resultMap="deptRM">
SELECT dept.*,emp.emp_id,emp.emp_name
FROM dept,emp
WHERE dept.dept_id=emp.dept_id
</select>
<!--
一对多封装:
1.collection: 封装集合类型
2.ofType: 指定集合内部(泛型)的对象类型
-->
<resultMap id="deptRM" type="Dept" autoMapping="true">
<!--主键必须标识-->
<id column="dept_id" property="deptId"/>
<!--一对多封装-->
<collection property="emps" ofType="Emp" autoMapping="true">
<id column="emp_id" property="empId"/>
</collection>
</resultMap>
五、使用分页插件分页查询
分类插件工具类
package com.example.demo.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* mybatisPlus分页插件
*/
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor page=new PaginationInnerInterceptor();
//选择mysql数据库进行分页
page.setDbType(DbType.MYSQL);
//true当输入页数大于实际页数时返回第一页数据,推荐
//false当输入页超出实际页面按输入页数情况返回
page.setOverflow(true);
interceptor.addInnerInterceptor(page);
return interceptor;
}
}
创建mybatis-plus条件构造器
LambdaQueryWrapper<UserTable> queryWrapper= new LambdaQueryWrapper<>();
创建分页条件page
//current 表示第1页,size 表示每页有3条数据
Page<UserTable> userTablePage=new Page<>(1,3);
往条件构造器添加分页条件和查询条件
//两个参数:第一个参数是page对象,第二个参数wrapper查询的条件,null表示查询无条件
loginMapper.selectPage(userTablePage, null);
获取分页查询所对应的数据
System.out.println("总页数:"+userTablePage.getPages());
System.out.println("当前页数"+userTablePage.getCurrent());
System.out.println("当前页记录数据"+userTablePage.getRecords());
System.out.println("每页记录数"+userTablePage.getSize());
System.out.println("总记录数"+userTablePage.getTotal());
System.out.println("是否有下一页"+userTablePage.hasNext());
System.out.println("是否有上一页"+userTablePage.hasPrevious());