删除
删除通过ID
@Test
public void testDeleteById(){
//通过id删除用户信息
//DELETE FROM user WHERE id=?
int result = userMapper.deleteById(1475754982694199298L);
System.out.println("受影响行数:"+result);
}
删除通过map
@Test
public void testDeleteByMap(){
Map<String,Object> map = new HashMap<String,Object>();
map.put("name","张三");
map.put("age",23);
userMapper.deleteByMap(map);
}
批量删除
@Test
public void testDeleteBatchIds(){
List<Long> idList = Arrays.asList(1L, 2L, 3L);
int result = userMapper.deleteBatchIds(idList);
System.out.println("受影响行数:"+result);
}
修改
@Test
public void testUpdate() {
User user = new User();
user.setId(4L);
user.setName("李四");
user.setEmail("lisi@qq.com");
userMapper.updateById(user);
System.out.println("user = " + user);
}
查询
根据ID查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println("user = " + user);
}
批量查询
@Test
public void testSelectBatchIds(){
List<Long> list = Arrays.asList(1L, 2L, 3L);
List<User> users = userMapper.selectBatchIds(list);
users.forEach(System.out::println);
}
根据Map查询
@Test
public void testSelectByMap(){
Map<String, Object> map = new HashMap<>();
map.put("name", "Jack");
map.put("age", 18);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
返回Map类型数据
/** 根据id查询用户信息为map集合 **/
Map<String,Object> selectMapById(Long id);
<select id="selectMapById" resultType="map">
select id,name,age,email from t_user where id = #{id}
</select>
条件构造器查询
Wrapper : 条件构造抽象类,最顶端父类
@Test
public void test01() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("user_name", "a")
.between("age", 20, 30)
.isNotNull("email");
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
@Test
public void test02() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("age")
.orderByAsc("uid");
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
@Test
public void test03() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.isNull("email");
int result = userMapper.delete(queryWrapper);
System.out.println("result = " + result);
}
@Test
public void test04() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.gt("age", 20)
.like("user_name", "a")
.or()
.isNotNull("email");
User user = new User();
user.setName("小明");
user.setEmail("test@atguigu.com");
int result = userMapper.update(user, queryWrapper);
System.out.println("result = " + result);
}
@Test
public void test05() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("user_name", "a")
.and(i -> i.gt("age", 20).or().isNull("email"));
User user = new User();
user.setName("小红");
user.setEmail("test@atguigu.com");
int result = userMapper.update(user, queryWrapper);
System.out.println("result = " + result);
}
@Test
public void test06() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("user_name", "age", "email");
List<Map<String, Object>> users = userMapper.selectMaps(queryWrapper);
users.forEach(System.out::println);
}
@Test
public void test07() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.inSql("uid", "select uid from t_user where uid <= 100");
List<User> list = userMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
UpdateWrapper
@Test
public void test08() {
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.like("user_name", "a")
.and(i -> i.gt("age", 20).or().isNull("email"));
updateWrapper.set("user_name", "小黑").set("email", "abc@atguigu.com");
int result = userMapper.update(null, updateWrapper);
System.out.println("result = " + result);
}
创建Service接口和实现类
查询总记录数
public interface UserService extends IService<User> {
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
@Autowired
private UserService userService;
@Test
public void testGetCount() {
long count = userService.count();
System.out.println("总记录数 = " + count);
}
@Test
public void testInsertMore() {
List<User> users = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
User user = new User();
user.setName("lxg" + i);
user.setAge(20 + i);
users.add(user);
}
boolean b = userService.saveBatch(users);
System.out.println(b);
}
业务层判断查询
@Test
public void test09() {
String username = "a";
Integer ageBegin = null;
Integer ageEnd = 30;
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
if (StringUtils.isNotBlank(username)) {
queryWrapper.like("user_name", username);
}
if (ageBegin != null) {
queryWrapper.gt("age", ageBegin);
}
if (ageEnd != null) {
queryWrapper.le("age", ageEnd);
}
List<User> list = userMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
判断
@Test
public void test10() {
String username = "a";
Integer ageBegin = null;
Integer ageEnd = 30;
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like(StringUtils.isNotBlank(username), "user_name", username)
.gt(ageBegin != null, "age", ageBegin)
.le(ageEnd != null, "age", ageEnd);
List<User> list = userMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
LambdaQueryWrapper
@Test
public void test11() {
String username = "a";
Integer ageBegin = null;
Integer ageEnd = 30;
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.like(StringUtils.isNotBlank(username), User::getName, username)
.gt(ageBegin != null, User::getAge, ageBegin)
.le(ageEnd != null, User::getAge, ageEnd);
List<User> list = userMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
LambdaUpdateWrapper
@Test
public void test12() {
LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.like(User::getName, "a")
.and(i -> i.gt(User::getAge, 20).or().isNull(User::getEmail));
updateWrapper.set(User::getName, "小黑").set(User::getEmail, "abc@atguigu.com");
int result = userMapper.update(null, updateWrapper);
System.out.println("result = " + result);
}
类映射
@TableName
@TableField("username")
@Tableld(value="uid",type=IdType.AUTO) 主键
@TableLogic 逻辑删除
global-config:
db-config:
table-prefix: t_
id-type: auto
分页
SpringBoot配置类
@Configuration
@MapperScan("scan.your.mapper.package")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
}
@Autowired
private ProductMapper productMapper;
@Test
public void testPage() {
Page<User> page = new Page<>(1, 3);
userMapper.selectPage(page, null);
System.out.println( page.getRecords());
System.out.println("总页数:" + page.getPages());
System.out.println("总记录数" + page.getTotal());
System.out.println("是否有上一页" + page.hasNext());
System.out.println("是否有下一页:" + page.hasPrevious());
}
自定义分页
Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);
<select id="selectPageVo" resultType="User">
select uid as `id`,user_name as `name`,age,email from t_user where age > #{age}
</select>
@Test
public void testSelectPageVo(){
Page<User> page = new Page<>(1, 5);
userMapper.selectPageVo(page, 20);
List<User> list = page.getRecords();
list.forEach(System.out::println);
System.out.println("当前页:"+page.getCurrent());
System.out.println("每页显示的条数:"+page.getSize());
System.out.println("总记录数:"+page.getTotal());
System.out.println("总页数:"+page.getPages());
System.out.println("是否有上一页:"+page.hasPrevious());
System.out.println("是否有下一页:"+page.hasNext());
}
乐观锁
类
package com.atguigu.mybatisplus.entity;
import lombok.Data;
@Data
public class Product {
private Long id;
private String name;
private Integer price;
@Version
private Integer version;
}
Mapper
@Repository
public interface ProductMapper extends BaseMapper<Product> {
}
@Test
public void testProduct01() {
Product productLi = productMapper.selectById(1);
System.out.println("小李查询的商品价格:" + productLi.getPrice());
Product productWang = productMapper.selectById(1);
System.out.println("小王查询的商品价格:" + productWang.getPrice());
productLi.setPrice(productLi.getPrice() + 50);
productMapper.updateById(productLi);
productWang.setPrice(productWang.getPrice() - 30);
int result = productMapper.updateById(productWang);
Product productBoss = productMapper.selectById(1);
System.out.println("老板查询的商品价格:" + productBoss.getPrice());
}
配置类
@Configuration
@MapperScan("com.atguigu.mybatisplus.mapper")
public class myBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
枚举
@Getter
public enum SexEnum {
MALE(1, "男"),
FEMALE(2, "女");
@EnumValue
private Integer sex;
private String sexName;
SexEnum(Integer sex, String sexName) {
this.sex = sex;
this.sexName = sexName;
}
}
配置application.yml
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
table-prefix: t_
id-type: auto
type-aliases-package: com.atguigu.mybatisplus.pojo
type-enums-package: com.atguigu.mybatisplus.enums
@SpringBootTest
public class MyBatisPlusEnumTest {
@Autowired
private UserMapper userMapper;
@Test
public void test() {
User user = new User();
user.setName("admin");
user.setAge(33);
user.setSex(SexEnum.MALE);
int result = userMapper.insert(user);
System.out.println("result = " + result);
}
}
逆向工程
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
public class FastAutoGeneratorTest {
public static void main(String[] args) {
String path = "/Users/luxiaogen/Documents/RoadTo2w/Java/尚硅谷/MyBatisPlus-2022/demo";
FastAutoGenerator.create("jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false", "root", "root")
.globalConfig(builder -> {
builder.author("atguigu")
.fileOverride()
.outputDir(path);
})
.packageConfig(builder -> {
builder.parent("com.atguigu")
.moduleName("mybatisplus")
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, path));
})
.strategyConfig(builder -> {
builder.addInclude("t_user")
.addTablePrefix("t_", "c_");
}).templateEngine(new FreemarkerTemplateEngine())
.execute();
}
}
主从数据源
@Service
@DS("master")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
|