redis实现分页查询+java+springboot
•
数据库
一:示例描述
Springboot+mp+redis
// 学生表 id sname cid
//班级表 cid cname
缓存注解一般是在service层
1.查询所有的班级 以及班级中的所有的信息 并能缓存 到rdis里面
(不要求分页)
2.Stream流 获取第二页的数据 ( 每页数据有2条)
二:实现
pom.xml依赖
org.springframework.boot
spring-boot-starter-data-redis
com.fasterxml.jackson.core
jackson-databind
2.12.4
com.baomidou
mybatis-plus-boot-starter
3.5.3
com.baomidou
mybatis-plus-generator
3.5.3
org.apache.velocity
velocity-engine-core
2.3
org.freemarker
freemarker
com.mysql
mysql-connector-j
runtime
com.alibaba
druid-spring-boot-starter
1.2.6
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
junit
junit
RELEASE
compile
com.alibaba
fastjson
1.2.15
application.properties
spring.redis.host=192.168.247.36 spring.redis.port=6379 spring.redis.password=chn spring.redis.database=0 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql:///od?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=root # ??? ?? ????java?util.Date ??????? spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 spring.jackson.serialization.write-date-keys-as-timestamps=false #logging.level.com.baomidou.ant.test.dao=debug #mybatis-plus tab_hjhj mybatis-plus.configuration.map-underscore-to-camel-case=true mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl #mybatis-plus.configuration.log-impl= mybatis-plus.mapper-locations=classpath:/mapper/*.xml #???? ???????0 ???1 mybatis-plus.global-config.db-config.logic-not-delete-value=0 mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus自动生成代码类
( entity,service,controller,mapper,controller层代码)
package com.aaa;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.fill.Column;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MyTest {
public static void main(String[] args) {
FastAutoGenerator.create("jdbc:mysql://localhost:3306/od","root","root")
// 全局配置
.globalConfig((scanner, builder) -> builder
.author("作者名字")
.outputDir("E:\\IDEA\\object\\springbootRedis03\\src\\main\\java")
)
// 包配置
.packageConfig(
(scanner, builder) ->
builder
.parent("com.aaa")
.pathInfo(Collections.singletonMap(OutputFile.xml, "E:\\IDEA\\object\\springbootRedis03\\src\\main\\resources\\mapper")))
// 策略配置
.strategyConfig((scanner, builder) -> builder.addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
.controllerBuilder().enableRestStyle().enableHyphenStyle()
.entityBuilder().enableLombok().addTableFills(
new Column("create_time", FieldFill.INSERT)
).build())
/*
模板引擎配置,默认 Velocity 可选模板引擎 Beetl 或 Freemarker
.templateEngine(new BeetlTemplateEngine())
.templateEngine(new FreemarkerTemplateEngine())
*/
.execute();
// 处理 all 情况
}
protected static List getTables(String tables) {
return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
}
具体数据库根据实际情况手动选择(我这里是od数据库下 classs表和student表)
redisConfig 序列化处理,缓存
package com.aaa.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate();
RedisSerializer redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setConnectionFactory(factory);
//key序列化方式
template.setKeySerializer(redisSerializer);
//value序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//value hashmap序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
/**
* 缓存处理
*
* @param factory
* @return
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题),过期时间600秒
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(600))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
return cacheManager;
}
}
@SpringBootApplication
@EnableCaching #开启缓存
public class SpringbootRedis03Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootRedis03Application.class, args);
}
}
entity层
@Data
public class Classs implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "cid", type = IdType.AUTO)
private Integer cid;
private String cname;
@TableField(exist = false)
private List studentList;
}
@Data
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "sid", type = IdType.AUTO)
private Integer sid;
private String sname;
private Integer cid;
}
service层
IClasssService.java
public interface IClasssService extends IService {
// @CachePut(value = "aClass",key = "#classs.cid")
public boolean add(Classs classs);
@CachePut(value = "dClass",key = "#cid")
boolean delete(Integer cid);
@CacheEvict(value = "gClass",key="#root.targetClass")
boolean update(Classs classs);
@Cacheable(value = "gClass")
public List getAll();
@Cacheable(value = "oClass")
public List gets(Integer pageNumber,Integer pageSize);
}
impl
@Service
public class ClasssServiceImpl extends ServiceImpl implements IClasssService {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private ClasssMapper cm;
@Override
@Cacheable(value = "gClass")
public List getAll() {
return cm.getAllc();
}
@Override
public boolean add(Classs classs) {
return this.save(classs);
}
@Override
public boolean delete(Integer cid) {
return this.removeById(cid);
}
@Override
public boolean update(Classs classs) {
return this.updateById(classs);
}
@Override
public List gets(Integer pageNumber,Integer pageSize) {
List allc = this.getAll();
List resultList = allc.stream()
.skip((pageNumber - 1) * pageSize) // 跳过前面的记录数
.limit(pageSize) // 获取指定数量的记录
.collect(Collectors.toList()); // 将结果收集到新的 List 中
return resultList;
}
}
mapper层
注解形式
@Mapper
public interface ClasssMapper extends BaseMapper {
@Select("select * from Classs")
@Results({
@Result(id = true, property = "cid", column = "cid"),
@Result(property = "studentList", column = "cid",
javaType = List.class,
many = @Many(select = "com.aaa.mapper.StudentMapper.getStudentByCid"))
})
List getAllc();
}
xml形式
select * from classs,student where classs.cid=student.cid
controller层
@RestController
@RequestMapping("/classs")
public class ClasssController {
@Autowired
private IClasssService iClasssService;
@PostMapping
public String add(@RequestBody Classs classs) {
boolean b = iClasssService.add(classs);
System.out.println(classs);
if (b) {
return "ok";
}
return "default";
}
@DeleteMapping("{cid}")
public String delete(@PathVariable Integer cid) {
boolean b = iClasssService.delete(cid);
if (b){
return "ok";
}
return "default";
}
@PutMapping
public String update(@RequestBody Classs classs){
boolean b = iClasssService.update(classs);
if (b){
return "ok";
}
return "default";
}
@GetMapping
public List get() {
return iClasssService.getAll();
}
@GetMapping("{pageNumber}/{pageSize}")
public List gets(@PathVariable Integer pageNumber,@PathVariable Integer pageSize) {
List list = iClasssService.gets(pageNumber, pageSize);
return list;
}
}
测试

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/9629ad8f60.html
