环境:SpringBoot 整合 MP下的进行,如有特殊环境会进行说明
一、添加操作
1 测试示例
/*测试添加*/@Testpublic void testInsert(){User user = new User();user.setName("应颠22");user.setAge(20);user.setEmail("zimu@lagou.com");// 返回值是影响的行数int result = userMapper.insert(user);System.out.println(result);System.out.println("id值为" + user.getId());}
执行结果 1 id值为1498597688496934913
可以看到,数据已经写入到了数据库,但是,id的值不正确,我们期望的是数据库自增长,实际是MP生 成了id的值写入到了数据库。 如何设置id的生成策略呢?
2 IdType
MP支持的id策略:
/** Copyright (c) 2011-2020, baomidou (jobob@qq.com).* <p>* Licensed under the Apache License, Version 2.0 (the "License"); you may not* use this file except in compliance with the License. You may obtain a copy of* the License at* <p>* https://www.apache.org/licenses/LICENSE-2.0* <p>* Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the* License for the specific language governing permissions and limitations under* the License.*/package com.baomidou.mybatisplus.annotation;import lombok.Getter;/*** 生成ID类型枚举类** @author hubin* @since 2015-11-10*/@Getterpublic enum IdType {/*** 数据库ID自增:需要库表已经设置为自增*/AUTO(0),/*** 该类型为未设置主键类型*/NONE(1),/*** 用户输入ID* <p>该类型可以通过自己注册自动填充插件进行填充</p>*/INPUT(2),/* 以下3种类型、只有当插入对象ID 为空,才自动填充。 *//*** 全局唯一ID (idWorker)*/ID_WORKER(3),/*** 全局唯一ID (UUID)*/UUID(4),/*** 字符串全局唯一ID (idWorker 的字符串表示)*/ID_WORKER_STR(5);private final int key;IdType(int key) {this.key = key;}}
修改User
package com.hua.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data // getter setter toString
@NoArgsConstructor
@AllArgsConstructor
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
注意:需要库表先开启自动增长
二、更新操作
在MP中,更新操作有2种,一种是根据id更新,另一种是根据条件更新。
1 根据id进行更新
@Test
public void testUpateById(){
User user = new User();
user.setId(6L);
user.setAge(30);
int i = userMapper.updateById(user);
System.out.println(i);
}
2 根据条件进行更新
/*
* 测试根据条件进行修改
*/
@Test
public void testUpate(){
// 1. 更新的字段
User user = new User();
user.setAge(35);
// 2.更新的条件
// com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name","子慕");
// 对于字段为空部分,不进行修改,即此处只修改年龄
int i = userMapper.update(user,queryWrapper);
System.out.println(i);
}
@Test
public void testUpate2(){
// com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("id",6).set("age",40);
int i = userMapper.update(null,updateWrapper);
System.out.println(i);
}
三、删除操作
1 deleteById
/*
* 根据ID进行删除
*/
@Test
public void testDeleteById(){
int i = userMapper.deleteById(2L);
System.out.println(i);
}
2 deleteByMap
/*
* 根据columnMap进行删除
*/
@Test
public void testDeleteByMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","子慕");
map.put("age",35);
// 将columnMap中的元素设置为删除的条件,多个条件是and的关系
int i = userMapper.deleteByMap(map);
System.out.println(i);
}
3 delete
@Test
public void testDelete(){
User user = new User();
user.setName("庆华");
user.setAge(26);
QueryWrapper<User> ueryWrapper = new QueryWrapper<>(user);
int i = userMapper.delete(ueryWrapper);
System.out.println(i);
}
@Test
public void testDelete(){
User user = new User();
QueryWrapper<User> ueryWrapper = new QueryWrapper<>(user);
ueryWrapper.eq("name","庆华").eq("age",26);
int i = userMapper.delete(ueryWrapper);
System.out.println(i);
}
// 下面代码无效执行
@Test
public void testDelete(){
User user = new User();
user.setName("华");
user.setAge(26);
QueryWrapper<User> ueryWrapper = new QueryWrapper<>(user);
ueryWrapper.eq("name","庆华").eq("age",26);
int i = userMapper.delete(ueryWrapper);
System.out.println(i);
}
上述两种方式不能共用
4 deleteBatchIds
@Test
public void testDeleteBatchIds(){
// 根据id集合批量删除
int i = userMapper.deleteBatchIds(Arrays.asList(10l,11l));
System.out.println(i);
}
四、查询操作
MP提供了多种查询操作,包括根据id查询、批量查询、查询单条数据、查询列表、分⻚查询等操作。
1 selectById
/*
根据ID进行查询
*/
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
2 selectBatchIds
/*
根据ID进行批量查询
*/
@Test
public void testSelectBatchIds(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1L, 3l));
for (User user : users) {
System.out.println(user);
}
}
3 selectOne
/*
测试selectOne
*/
@Test
public void testSelectOne(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name","华");
// 根据条件查询一条记录,如果查询结果超过一条,会报错
User user = userMapper.selectOne(queryWrapper);
System.out.println(user);
}
4 selectCount
/*
根据wrapper条件,查询总记录数
*/
@Test
public void testSelectCount(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",18); // 查询年龄大于18的
Integer count = userMapper.selectCount(queryWrapper);
System.out.println(count);
}
5 selectList
/*
根据wrapper条件,查询总记录数
*/
@Test
public void testSelectCount(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",18); // 查询年龄大于18的
List<User> users = userMapper.selectList(queryWrapper);
for (User user : users) {
System.out.println(user);
}
}
五、分页查询
1 方法定义
/**
* 根据 entity 条件,查询全部记录(并翻⻚)
*
* @param page 分⻚查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
2 分页插件配置
2.1 SpringBoot配置
package com.hua.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
//@MapperScan("com.hua.mapper") //设置mapper接⼝的扫描包
public class MybatisPlusConfig {
/**
* 分⻚插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
2.1 普通maven工程配置
在sqlMapConfig.xml核心配置文件中进行配置
<?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>
<plugins>
<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></plugin>
</plugins>
</configuration>
2.3 spring工程配置
在2.1的基础上配置 applicationContext.xml。
<!--1. 将sqlSessionFactory对象的创建交给spring-->
<bean id="sqlSessionFactory"
class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--引入mybatis的核心配置文件-->
<property name="configLocation" value="classpath:sqlMapConfig.xml"/>
</bean>
3 具体测试
@Test
public void testSelectPage(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age",18); // 查询年龄大于18的
// 第一个参数:当前页 第二个参数:每页显示条数
Page<User> page = new Page<>(1, 2);
IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);
System.out.println("总条数" + userIPage.getTotal());
System.out.println("总页数" + userIPage.getPages());
System.out.println("分页数据" + userIPage.getRecords());
}
测试结果 总条数5 总页数3 分页数据[User(id=3, name=Tom, age=28, mail=test3@baomidou.com, address=null), User(id=4, name=Sandy, age=21, mail=test4@baomidou.com, address=null)]
可以看到,数据已经写入到了数据库,但是,id的值不正确,我们期望的是数据库自增长,实际是MP生 成了id的值写入到了数据库。
如何设置id的生成策略呢?