spring boot+mybatis-plus+mysql
spring boot+mybatis-plus+mysql
·
1、版本:spring boot 2.7 +mybatis-plus 3.4
2、安装mybatis-plus依赖项
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
3、表结构
4、项目结构
5、实体类
package com.example.springbootmybatisplus.pojo;
import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@TableName("user")
@Data
public class User {
//对应数据库的主键(uuid,自增id,雪花算法,redis,zookper)
@TableId(type = IdType.AUTO)
private long id;
private String name;
private Integer age;
private String email;
//逻辑删除字段
@TableLogic //逻辑删除注解
private Integer deleted;
//字段添加填充内容
//策略
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
//策略
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
注意:如果项目采用分层VO的话,对于处理返回前端多余字段需要加上@JsonInclude(JsonInclude.Include.NON_NULL)注解即可,那么则对于不需要的字段前端就不显示了
6、配置文件
server.port=xxxxx
#mysql连接配置,与mybatis一致
spring.datasource.url=jdbc:mysql://localhost:3306/xxxx?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=xxxxxx
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
#mybatis-plus日志配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
7、启动文件配置mapper路径
package com.example.springbootmybatisplus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//扫描mapper文件夹
@MapperScan("com.example.springbootmybatisplus.mapper")
@SpringBootApplication
public class SpringbootmybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootmybatisplusApplication.class, args);
}
}
8、dao层代码
package com.example.springbootmybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootmybatisplus.pojo.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper<User> {
}
9、create_time,update_time自动生成处理器配置类
package com.example.springbootmybatisplus.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component //一定不要忘记把处理器加到IOC容器中
public class MyDataObjectHandler implements MetaObjectHandler {
//插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill");
//setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
this.setFieldValByName("createTime",LocalDateTime.now(),metaObject);
this.setFieldValByName("updateTime",LocalDateTime.now(),metaObject);
}
//更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
10、mybatis-plus分页插件配置类
package com.example.springbootmybatisplus.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//@EnableTransactionManagement
@Configuration // 配置类
public class MyBatisPlusConfig {
//分页
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
//@Bean public ISqlInjector sqlInjector() { return new LogicSqlInjector(); }
}
11、引入dao的mapper操作对象
@Autowired
private UserMapper userMapper;
12、测试查询部分
//测试查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1000L);
System.out.println(user);
}
@Test
//批量查询
public void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(4, 5, 8, 9));
System.out.println(users);
}
//条件查询 map
@Test
public void testSelectByBatchIds(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","mybatis-plus-test");
map.put("age",89);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
13、测试分页查询部分
@Test
//测试分页查询
public void testPage(){
//参数一:当前页
//参数二:页面大小
Page<User> page = new Page<>(1,5);
Page<User> userPage = userMapper.selectPage(page, null);
// page.getRecords().forEach(System.out::println);
// //获取总数
// System.out.println("总数:");
// System.out.println(page.getTotal());
System.out.println("查询结果");
System.out.println(userPage.getRecords());
System.out.println("总数");
System.out.println(userPage.getTotal());
}
14、测试插入部分
//测试插入功能
@Test
public void testInsert(){
User user = new User();
user.setName("mybatis-18-plus-test18");
user.setAge(18);
user.setEmail("mabat-18test@qq.com");
int result=userMapper.insert(user);
System.out.println(result);
System.out.println(user);
System.out.println(user.getId());
}
15、测试更新部分
//更新
@Test
public void testUpdate(){
User user = new User();
user.setId(10L);
user.setName("mybatis-plus-test");
int i=userMapper.updateById(user);
System.out.println(i);
}
16、测试删除部分(如何逻辑删除需在实体类做配置)
//删除操作
@Test
public void testDeleteById(){
int rows = userMapper.deleteById(1000L);
System.out.println(rows);
}
//批量删除根据ID
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(996,997,998));
}
//通过map删除
@Test
public void testDeleteMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","叔叔婶婶");
userMapper.deleteByMap(map);
}
17、注:实体类的时间映射,添加注解@JsonFormat(pattern = “yyyy-MM-dd”, timezone = “GMT+8”)
18、当updateById时,如果要插入空值,则在实体类上新增注解@TableField(updateStrategy = FieldStrategy.IGNORED)即可
更多推荐
已为社区贡献18条内容
所有评论(0)