# Host: localhost (Version 5.7.23-log)
# Date: 2023-12-10 14:21:50
# Generator: MySQL-Front 6.0 (Build 2.20)
#
# Structure for table "tb_user"
#
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL COMMENT '用户名',
`password` varchar(32) DEFAULT NULL COMMENT '密码',
`role` varchar(10) DEFAULT NULL COMMENT '角色:0:管理员 1:普通用户',
`sex` int(11) DEFAULT NULL COMMENT '性别,0:女 1:男',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`createTime` datetime DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
#
# Data for table "tb_user"
#
INSERT INTO `tb_user` VALUES (1,'admin','123456','0',1,25,'2022-10-23 00:12:36'),(6,'张曼玉','123456','1',1,18,'2022-10-23 00:12:44'),(14,'a3','122','1',1,313,'2023-10-17 21:31:48'),(15,'aaa','123456','1',1,111,'2023-11-13 20:26:10'),(17,'aaa','weqe','1',0,NULL,'2023-11-20 18:33:09');
com.baomidou
mybatis-plus-boot-starter
3.5.2
mysql
mysql-connector-java
8.0.30
org.projectlombok
lombok
1.18.24
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3307/mybatis?
useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
package com.cqh.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data //@Data : 注解在类上,提供类的get、set、equals、hashCode、canEqual、toString、无参构造方法,没有有参构造方法。
@AllArgsConstructor // 全部参数构造方法
@NoArgsConstructor //无参数构造方法
@TableName("tb_user")
public class User {
@TableId
private int id;
private String username;
private String password;
private String role;
private int sex;
private int age;
@TableField(value = "createTime")
private Date createTime;
}
package com.cqh;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.cqh.mapper")
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class,args);
}
}
package com.cqh;
import com.cqh.entity.User;
import com.cqh.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
//查询全部用户
//此方法需要我们传递Wrapper对象,此对象是条件构造器,我们现在要查询全部用户先不用,所以传null即可
@Test
public void test01(){
List users = userMapper.selectList(null);
for (User user : users) {
System.out.println("user = " + user);
}
}
}
# 配置日志
mybatis-plus.configuration.logimpl=org.apache.ibatis.logging.stdout.StdOutImpl
//插入数据
@Test
public void test02(){
User user1 = new User();
user1.setUsername("xiaoMin");
user1.setPassword("123456");
user1.setAge(11);
user1.setRole("0");
user1.setSex(1);
int insert = userMapper.insert(user1);
System.out.println("insert = " + insert);
}
Serializable
的参数 id
,表示要删除的记录的唯一标识符。
//根据map删除
@Test
public void deleteTest(){
Map map = new HashMap<>();
map.put("username","xiaoMin");
map.put("age",11);
int num = userMapper.deleteByMap(map);
System.out.println(num);
}
//根据多个id进行批量删除
@Test
public void deleteTest2(){
ArrayList ids = new ArrayList<>();
ids.add(15);
ids.add(17);
int num = userMapper.deleteBatchIds(ids);
System.out.println(num);
}
//根据多个条件进行删除
@Test
public void deleteTest3(){
QueryWrapper userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.eq("username","a3");
userQueryWrapper.eq("sex",1);
int num = userMapper.delete(userQueryWrapper);
System.out.println(num);
}
修改方法BaseMapper中提供了两个
//根据id修改
@Test
public void updateTest(){
User user = new User();
user.setId(6);
user.setUsername("李四");
int num = userMapper.updateById(user);
System.out.println(num);
}
//根据Map中传递的条件进行查询
@Test
public void selectTest(){
Map map = new HashMap<>();
map.put("id",6);
map.put("username","李四");
List users = userMapper.selectByMap(map);
users.forEach(user -> System.out.println(user));
}
此方法Wrapper条件构造器传递参数为null表示查询全部数据
//插入数据
@Test
public void test02(){
User user1 = new User();
user1.setUsername("xiaoMin");
user1.setPassword("123456");
user1.setAge(11);
user1.setRole("0");
user1.setSex(1);
int insert = userMapper.insert(user1);
System.out.println("insert = " + insert);
}
有一个问题就是没有主键返回
(注意:表一定要是主键自增 )
修改User实体类
编写mapper
package com.cqh.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cqh.entity.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserMapper extends BaseMapper {
/**
* 根据name查询数据
* @param username
* @return
*/
@Select("select * from tb_user where username=#{username}")
List selectByName(String username);
}
编写测试方法
package com.cqh.config;
/**
* @author cqh
* @date 2023/12/10
* @Description
*/
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
//开启扫描,注意包名不要写错(有了MyBatisPlus的配置类,我们就可以把所有的相关配置都写在这里)
@MapperScan("com.qf.mybatisplusdemo.mapper")
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new
MybatisPlusInterceptor();
//分页插件
mybatisPlusInterceptor.addInnerInterceptor(new
PaginationInnerInterceptor(DbType.MYSQL));
return mybatisPlusInterceptor;
}
}
@Test
public void PaginationInnerInterceptorTest(){
//简单分页模型 current:第几页 size:显示几条数据
//底层逻辑就是使用Limit分页的公式 (index-1)*pageSize
Page page = new Page<>(1,3);
//条件构造器Wrapper目前没有就写null
userMapper.selectPage(page,null);
}
@Test
public void PaginationInnerInterceptorTest2(){
//简单分页模型 current:第几页 size:显示几条数据
//底层逻辑就是使用Limit分页的公式 (index-1)*pageSize
Page page = new Page<>(2,3);
//条件构造器Wrapper目前没有就写null
userMapper.selectPage(page,null);
//获取记录
List users = page.getRecords();
users.forEach(user -> System.out.println(user));
System.out.println(page.getPages()); //获取总页数
System.out.println(page.getTotal()); //获取总数据量
System.out.println(page.hasNext());//是否有下一页
System.out.println(page.hasPrevious());//是否有上一页
}
我这里 查询username不为空的用户,并且年龄大于10岁
比较用的.ge() 这是大于等于
还有许多比较方法
// 查询名字为chen的用户
// 查询年龄18~25岁之间的用户
// 查询年龄大于等于25岁的用户
// 模糊查询:查询名字不包含a的用户,反之like就是包含
//模糊查询:包含左侧或者右侧具体内容
子查询
//修改用户id为24的username为jack
//修改年龄大于等于10,并且username为xiao的用户role为 0
package com.cqh;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqh.entity.User;
import com.cqh.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
//查询全部
@Test
public void test01(){
List users = userMapper.selectList(null);
for (User user : users) {
System.out.println("user = " + user);
}
}
//插入数据
@Test
public void test02(){
User user1 = new User();
user1.setUsername("chen1");
user1.setPassword("123456");
user1.setAge(18);
user1.setRole("1");
user1.setSex(1);
int insert = userMapper.insert(user1);
System.out.println("insert = " + insert);
System.out.println("id = " + user1.getId());
}
//根据map删除
@Test
public void deleteTest(){
Map map = new HashMap<>();
map.put("username","xiaoMin");
map.put("age",11);
int num = userMapper.deleteByMap(map);
System.out.println(num);
}
//根据多个id进行批量删除
@Test
public void deleteTest2(){
ArrayList ids = new ArrayList<>();
ids.add(15);
ids.add(17);
int num = userMapper.deleteBatchIds(ids);
System.out.println(num);
}
//根据多个条件进行删除
@Test
public void deleteTest3(){
QueryWrapper userQueryWrapper = new QueryWrapper<>();
userQueryWrapper.eq("username","a3");
userQueryWrapper.eq("sex",1);
int num = userMapper.delete(userQueryWrapper);
System.out.println(num);
}
//根据id修改
@Test
public void updateTest(){
User user = new User();
user.setId(6);
user.setUsername("李四");
int num = userMapper.updateById(user);
System.out.println(num);
}
//根据Map中传递的条件进行查询
@Test
public void selectTest(){
Map map = new HashMap<>();
map.put("id",6);
map.put("username","李四");
List users = userMapper.selectByMap(map);
users.forEach(user -> System.out.println(user));
}
@Test
public void selectByNameTest(){
List users = userMapper.selectByName("李四");
users.forEach(user -> System.out.println(user));
}
@Test
public void PaginationInnerInterceptorTest(){
//简单分页模型 current:第几页 size:显示几条数据
//底层逻辑就是使用Limit分页的公式 (index-1)*pageSize
Page page = new Page<>(1,3);
//条件构造器Wrapper目前没有就写null
userMapper.selectPage(page,null);
}
@Test
public void PaginationInnerInterceptorTest2(){
//简单分页模型 current:第几页 size:显示几条数据
//底层逻辑就是使用Limit分页的公式 (index-1)*pageSize
Page page = new Page<>(2,3);
//条件构造器Wrapper目前没有就写null
userMapper.selectPage(page,null);
//获取记录
List users = page.getRecords();
users.forEach(user -> System.out.println(user));
System.out.println(page.getPages()); //获取总页数
System.out.println(page.getTotal()); //获取总数据量
System.out.println(page.hasNext());//是否有下一页
System.out.println(page.hasPrevious());//是否有上一页
}
// 查询username不为空的用户,并且年龄大于10岁
@Test
public void selectTest1(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.isNotNull("username")
.ge("age",10);
userMapper.selectList(wrapper).forEach(System.out::println);//类似于map传入条件
}
// 查询名字为chen的用户
@Test
public void selectTest2(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.eq("username","chen");
User user = userMapper.selectOne(wrapper);//类似于map传入条件
System.out.println(user);
}
// 查询年龄18~25岁之间的用户
@Test
public void selectTest3(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.between("age",18,25);
userMapper.selectList(wrapper).forEach(System.out::println);//类似于map传入条件
}
// 查询年龄大于等于25岁的用户
@Test
public void selectTest4(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.ge("age",25);
userMapper.selectList(wrapper).forEach(System.out::println);//类似于map传入条件
}
// 模糊查询:查询名字不包含a的用户,反之like就是包含
@Test
public void selectTest5(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.notLike("username","a");
userMapper.selectList(wrapper).forEach(System.out::println);//类似于map传入条件
}
//模糊查询:包含左侧或者右侧具体内容
@Test
public void selectTest6(){
QueryWrapper wrapper = new QueryWrapper<>();
// 模糊查询:查询名字不包含qf的用户,反之like就是包含
// likeLeft和likeRight
// 左右就是 %在左或者在右
// 以下就是 a% 相当于以a开头的名字
wrapper.likeRight("username","a");
userMapper.selectList(wrapper).forEach(System.out::println);//类似于map传入条件
}
//通过子查询,查询id等于6的用户信息,此方法也可以进行表关联查询
@Test
public void selectTest7(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.inSql("id","select id from tb_user where id=6");
userMapper.selectObjs(wrapper).forEach(System.out::println);
}
// 查询用户名中包含a并且年龄大于29或者crateTime为空的用户
@Test
public void selectTest8(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.like("username","a")
.and(w->w.gt("age",26).or().isNull("createTime"));
userMapper.selectList(wrapper).forEach(System.out::println);
}
// 模糊查询:查询名字包含a的用户,并且按照age升序排序,注意参数不能为空
@Test
public void selectTest9(){
//假设用户传递参数
String username = "a";
Integer age = 1;
//先判断条件是否符合,符合才会组合到SQL语句中
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.like(StringUtils.isNotBlank(username),"username",username)
.orderByAsc(age != null,"age");
userMapper.selectList(wrapper).forEach(System.out::println);//类似于map传入条件
}
//修改用户id为24的username为jack
@Test
public void updateTest1(){
// QueryWrapper wrapper = new QueryWrapper<>();
// wrapper.eq("id",24);
User user = new User();
user.setUsername("jack");
// userMapper.update(user,wrapper);
userMapper.update(user,new QueryWrapper().eq("id",24));
}
//删除username为jack的用户
@Test
public void deleteTest1(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.eq("username","jack");
userMapper.delete(wrapper);
}
//修改年龄大于10,并且username为xiao的用户role为 0
@Test
public void updateTest2(){
UpdateWrapper wrapper = new UpdateWrapper<>();
wrapper.gt("age",10)
.eq("username","xiao")
.set("role","0");
//无需传递user对象,直接赋值为null
userMapper.update(null,wrapper);
}
@Test
public void selectTest10(){
//假设用户传递参数
String username = "a";
Integer age = null;
//LambdaQueryWrapper就是为了防止我们写错字段,可以直接通过Lambda的方式来直接获取指定字段对应的实体类对应的名称
LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();
wrapper.like(StringUtils.isNotBlank(username),User::getUsername,username)
.orderByAsc(age != null,User::getAge);
userMapper.selectList(wrapper).forEach(System.out::println);//类似于map传入条件
}
//修改年龄大于10,并且name为xiao的用户role为 1
@Test
public void updateTest3(){
LambdaUpdateWrapper wrapper = new LambdaUpdateWrapper<>();
wrapper.gt(User::getAge,10)
.eq(User::getUsername,"xiao")
.set(User::getRole,"1");
//无需传递user对象,直接赋值为null
userMapper.update(null,wrapper);
}
}