1.依赖
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>3.4.2</version></dependency>
如果想在mybatis-plus自行是看打印的sql,可配置:
#mybatis-plus配置控制台打印完整带参数SQL语句
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
2.编码
实体类:
package com.itheima.sh.pojo;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
/**
* @Description:
* @Version: V1.0
*/
@TableName("tb_user") // 指定表名 如果数据库的表名和实体类一致时可以省略
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {
private Long id;
private String userName;
private String password;
private String name;
private Integer age;
private String email;
}
编写mapper:
package com.itheima.sh.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.itheima.sh.pojo.User;
/**
* 使用mp定义Mapper,需要让Mapper接口继承 BaseMapper接口。
*/
public interface UserMapper extends BaseMapper<User> {
}
启动类增加 @MapperScan 注解:
package com.itheima.sh;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.itheima.sh.mapper")
public class MpApplication {
public static void main(String[] args) {
SpringApplication.run(MpApplication.class, args);
}
}
3.MP实现常规增删改操作
@Test
public void testInsert() {
User user =
User.builder()
.userName("itheima")
.name("itcast")
.age(15)
.email("itcast@itcast.cn")
.password("111111")
.build();
int insert = userMapper.insert(user);
System.out.println(insert);
}
@TableId注解作用:
1.标识实体类中主键对应属性;
2.定义主键生成策略;
@TableId使用:
添加在实体类的主键对应的成员属性上即可;
MP提供的常用主键生成策略如下:
| 生成策略 | 应用场景 | 特点 |
|---|---|---|
| IdType.AUTO | 数据库主键自增(确保数据库设置了 主键自增 否则无效) | 1.使用数据库自带的主键自增值; 2.数据库自增的主键值会回填到实体类中; 3.数据库服务端生成的; |
| IdType.ASSIGN_ID | 主键类型为number类型或数字类型String | 1.MP客户端生成的主键值; 2.生成的主键值是数字形式的字符串 3.主键对应的类型可以是数字类型或者数字类型的字符串 4.底层基于雪花算法,让数据库的唯一标识也参与id的生成运算,保证id在分布式环境下,全局唯一(避免id的主键冲突问题); |
| IdType.ASSIGN_UUID | 主键类型为 string(包含数字和字母组成) | 1.生成的主键值包含数字和字母组成的字符串; 2.注意事项:如果数据库中主键值是number类型的,可不可用 |
普通列注解-@TableField
通过@TableField(“表列名”) 指定映射关系
以下情况可以省略:
- 名称一样
- 数据库字段使用_分割,实体类属性名使用驼峰名称(自动开启驼峰映射)
2.忽略某个字段的查询和插入 ` @TableField(exist = false)
删除方法
//根据id删除
int count = userMapper.deleteById(8L);
//根据id集合批量删除
List ids = new ArrayList();
ids.add(6);
ids.add(7);
userMapper.deleteBatchIds(ids);
//根据map构造条件,删除
Map<String, Object> map = new HashMap<>();
//delete from tb_user where user_name = ? and age = ?
map.put("user_name","itcast");
map.put("age","18");
userMapper.deleteByMap(map);
//MP实现更新操作
@Test
public void testUpdateById() {
User user = new User();
user.setId(2L);
user.setPassword("1111111");
int count = userMapper.updateById(user);
}
MP实现查询操作
MP实现分页查询
①配置分页拦截器
package com.itheima.sh.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;
/**
* @Description:
* @Version: V1.0
*/
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,-1不受限制
paginationInterceptor.setMaxLimit(-1L);
interceptor.addInnerInterceptor(paginationInterceptor);
return interceptor;
}
}
/**
* 分页查询:
* 1. 当前页码:currentPage
* 2. 每页显示条数:size
*
* 注意:使用mp的分页要设置一个拦截器!!!
*/
@Test
public void testSelectPage() {
int current = 1;//当前页码
int size = 2;//每页显示条数
IPage<User> page = new Page(current,size);
userMapper.selectPage(page,null);
List<User> records = page.getRecords();//当前页的数据
long pages = page.getPages();//总页数 2
long total = page.getTotal();//总记录数 4
System.out.println(records);
System.out.println(pages);
System.out.println(total);
}
QueryWrapper实现基础查询
/**
* 基础比较查询
*
* Wrapper接口:
* 1.QueryWrapper
* LambdaQueryWrapper
* 2.UpdateWrapper
* LambdaUpdateWrapper
*/
eq( ) : 等于 =
ne( ) : 不等于 <>
gt( ) : 大于 >
ge( ) : 大于等于 >=
lt( ) : 小于 <
le( ) : 小于等于 <=
between ( ) : BETWEEN 值1 AND 值2
notBetween ( ) : NOT BETWEEN 值1 AND 值2
in( ) : in
notIn( ) :not in
要求:查询用户中姓名包含”伤”,密码为”123456”,且年龄为19或者25或者29,查询结果按照年龄降序排序;
@Test
public void testWrapper1() throws Exception{
QueryWrapper<User> wrapper = new QueryWrapper<>();
// 封装查询条件
wrapper.like("user_name", "伤")
.eq("password","123456")
.in("age",19,25,29)
.orderByDesc("age","id"); // 降序 升序:asc
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
QueryWrapper逻辑查询or
@Test
public void testWrapper2(){
//1.创建查询条件构建器
QueryWrapper<User> wrapper = new QueryWrapper<>();
//2.设置条件
wrapper.eq("user_name","lisi")
.or()
.lt("age",23)
.in("name","李四","王五");
/*
select * from tb_user where user_name = ? or age < ? and name in (?,?)
*/
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
QueryWrapper模糊查询like
/**
* 模糊查询
*/
@Test
public void testWrapper3(){
//1.创建查询条件构建器
QueryWrapper<User> wrapper = new QueryWrapper<>();
//2.设置条件
wrapper.likeLeft("user_name","zhang");
/*
SELECT id,user_name,password,name,age,email
from tb_user
where user_name like ?
%zhang
*/
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
QueryWrapper排序查询
@Test
public void testWrapper4(){
//1.创建查询条件构建器
QueryWrapper<User> wrapper = new QueryWrapper<>();
//2.设置条件
wrapper.eq("user_name","lisi")
.or()
.lt("age",23)
.in("name","李四","王五")
//.orderBy(true,true,"age")
.orderByDesc("age");
/*
select * from tb_user where user_name = ? or age < ? and name in (?,?) order by age asc
*/
List<User> users = userMapper.selectList(wrapper);
System.out.println(users);
}
