SpringBoot项目引入MybatisPlus
mybatis-plus是对mybatis的一个简化和升级。
核心是给所有的Mapper接口抽取了一个父接口,让所有的Mapper接口继承父接口来实现;给所有的Service接口也抽取了一个父接口,让所有的Service接口也继承父接口来实现。
第一步:
导入依赖
<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>
第二步:
配置文件
#应用名称 spring.application.name=SbmpDemo #应用服务访问端口 server.port=8080 #-------------------------配置数据源--------------------------------------- spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/db_mp?serverTimezone=UTC spring.datasource.username=root spring.datasource.password=1234 #-----配置mybatis-plus(和mybatis的配置一样,只是属性前缀变为了mybatis-plus)----- #注册sql映射文件(resources/mapper/*.xml) mybatis-plus.mapper-locations=classpath:mapper/*.xml #输出日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl #开启驼峰命名规则 mybatis-plus.configuration.map-underscore-to-camel-case=true
第三步:
启动类或mapper接口上添加注解
//启动类添加注解,表示开启包扫描 @MapperScan(basePackages = "com.xxx.mapper")
或
//在mapper接口上添加注解 @Mapper
分页查询:
service.page();
mapper.selectPage();
多行查询:
service.list();
Wrapper条件对象的方法:
一般new它的子类对象:
LambdaQueryWrapper<>对象和QueryWrapper<>对象
eq(String column, V) -- 等于 ne(String column, V) -- 不等于 gt(String column, V) -- 大于 ge(String column, V) - -大于等于 lt(String column, V) -- 小于 le(String column, V) -- 小于等于 allEq(Map<String column, V>) -- 全等于 between(String column, V1, V2) -- between and in(String column, Object...Values) -- in like(String column, V) -- like模糊查询 orderByAsc(String column) -- 升序排序 orderByDesc(String column) -- 降序排序 groupBy(String column) -- 分组
关于事务
对数据库增删改的方法上可添加注解
@Transactional(rollbackFor = Exception.class)
关于缓存
代码注入redis中进行缓存
//先判断redis中是否已经有缓存的数据了 String redis_value = redisTemplate.opsForValue().get("键"); //有的话转换为需要返回的对象,然后返回即可 return JSON.parseArray(redis_value,需要返回的类.class);
//查询数据后,转换为json字符串 String jsonStr = JSON.toJSONString(查询到的数据); //存入redis redisTemplate.opsForValue().set("键",jsonStr, Duration.ofDays(7));
注解注入redis
@EnableCaching //在启动类上加上注解启动缓存 //作用在你要缓存的数据上 @Cacheable//在方法上添加注解(添加缓存) @Cacheput //在方法上添加注解;解决脏读 每次都会执行一次数据库查询,然后把查到的值存入缓存中 一般用于更新 @CachEvict//在方法上添加注解;(解决脏读) @CacheConfig//在类上添加注解;(全局的配置缓存)
//注解式存储的时候,因为会自动将返回的数据转换为json数据 //所以需要实体类实现Serializable接口