
redis实现分页查询+java+springboot
一:示例描述// 学生表id sname cid//班级表cid cname缓存注解一般是在service层1.查询所有的班级以及班级中的所有的信息 并能缓存 到rdis里面(不要求分页)2.Stream流 获取第二页的数据 ( 每页数据有2条)二:实现。
·
一:示例描述
Springboot+mp+redis
// 学生表 id sname cid
//班级表 cid cname
缓存注解一般是在service层
1.查询所有的班级 以及班级中的所有的信息 并能缓存 到rdis里面
(不要求分页)
2.Stream流 获取第二页的数据 ( 每页数据有2条)
二:实现
pom.xml依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
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<String> 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<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
RedisSerializer<String> 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<String> 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<Student> 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<Classs> {
// @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<Classs> getAll();
@Cacheable(value = "oClass")
public List<Classs> gets(Integer pageNumber,Integer pageSize);
}
impl
@Service
public class ClasssServiceImpl extends ServiceImpl<ClasssMapper, Classs> implements IClasssService {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private ClasssMapper cm;
@Override
@Cacheable(value = "gClass")
public List<Classs> 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<Classs> gets(Integer pageNumber,Integer pageSize) {
List<Classs> allc = this.getAll();
List<Classs> resultList = allc.stream()
.skip((pageNumber - 1) * pageSize) // 跳过前面的记录数
.limit(pageSize) // 获取指定数量的记录
.collect(Collectors.toList()); // 将结果收集到新的 List 中
return resultList;
}
}
mapper层
注解形式
@Mapper
public interface ClasssMapper extends BaseMapper<Classs> {
@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<Classs> getAllc();
}
xml形式
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aaa.mapper.ClasssMapper">
<resultMap id="lls" type="com.aaa.entity.Classs" autoMapping="true">
<id property="cid" column="cid"></id>
<collection property="studentList" ofType="com.aaa.entity.Student" autoMapping="true">
<id property="cid" column="cid"></id>
</collection>
</resultMap>
<select id="cid" resultMap="lls">
select * from classs,student where classs.cid=student.cid
</select>
</mapper>
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<Classs> get() {
return iClasssService.getAll();
}
@GetMapping("{pageNumber}/{pageSize}")
public List<Classs> gets(@PathVariable Integer pageNumber,@PathVariable Integer pageSize) {
List<Classs> list = iClasssService.gets(pageNumber, pageSize);
return list;
}
}
测试
更多推荐
所有评论(0)