现在的位置: 首页 > 编程语言 > 正文

如何使用SpEL表达式实现动态分表查询

2020年02月13日 编程语言 ⁄ 共 2144字 ⁄ 字号 评论关闭

这篇文章主要介绍了如何使用SpEL表达式实现动态分表查询,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

这里的动态分表查询并不是动态构造sql语句,而是利用SpEL操作同一结构的不同张表。

也可以参考Spring Data Jpa中的章节http://docs.spring.io/spring-data/jpa/docs/1.11.3.RELEASE/reference/html/#jpa.query.spel-expressions

背景如下:

因为数据量较大,将数据按年份进行了分表,表结构都是一致的。例如现在有两张表分别表示2017/2018年数据

表中只有id和name两个字段

DROP TABLE IF EXISTS "public"."data_2017";CREATE TABLE "public"."data_2017" ("id" int4 NOT NULL,"name" varchar(255) COLLATE "default")WITH (OIDS=FALSE)

实际工作中们需要根据请求去选择查询17年的表还是18年的表。执行的sql语句除了表名不一致,其他均一致。

SELECT id,name FROM table

利用JPA实现

因为JPA中实体与表示一一对应的,而实际查询的语句又是一样的,那么如果按照传统JPA方法,就需要建立N个Entity,N个Repository,N个查询方法。

现在使用SpELl表达式可以简化Entity及Repository中的代码编写,相对提高效率。

1、建立一个抽象实体

/*** Created by dingshuo on 2017/6/5.*/@MappedSuperclasspublic class AbstractMappedType {private int id;private String name;@Id@Column(name = "id")@JsonIgnorepublic int getId() {return id;}public void setId(int id) {this.id = id;}@Column(name = "name")public String getName() {return name;}public void setName(String name) {this.name = name;}}

2、建立17/18年表对应的实体,继承抽象实体

/*** Created by dingshuo on 2017/6/5.*/@Entity@Table(name = "DATA_2017", schema = "public", catalog = "powermanager")public class Data2017 extends AbstractMappedType {}/*** Created by dingshuo on 2017/6/5.*/@Entity@Table(name = "DATA_2018", schema = "public", catalog = "powermanager")public class Data2018 extends AbstractMappedType {}

3、建立抽象Repository

/*** Created by dingshuo on 2017/6/5.*/@NoRepositoryBeanpublic interface MappedTypeRepository<T extends AbstractMappedType>extends Repository<T, Long> {@Query("select t from #{#entityName} t where t.id = ?1")List<T> findById(int id);@Query("select t from #{#entityName} t ")List<T> findALL();}

4、建立17年实体的Repository,继承抽象Repository

/*** Created by dingshuo on 2017/6/5.*/public interface Data2017Repository extends MappedTypeRepository<Data2017>{}

5、测试

@RestControllerpublic class TestController {@AutowiredData2017Repository repository;@GetMapping(value = "/test")public String test(){List<Data2017> object=repository.findById(1);List<Data2017> objec1t=repository.findALL();return "OK";}}

如上就可以相对简化的使用JPA查询结构相同,表名不同的系列表数据了。

当然,还是得建立N个Entity和N个Repository,还是比较麻烦的。。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: 如何使用SpEL表达式实现动态分表查询

以上就上有关如何使用SpEL表达式实现动态分表查询的相关介绍,要了解更多SpEL,表达式,动态,分表查询内容请登录学步园。

抱歉!评论已关闭.