利用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.
*/
@MappedSuperclass
public class AbstractMappedType {
private int id;
private String name;
@Id
@Column(name = "id")
@JsonIgnore
public 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.
*/
@NoRepositoryBean
public 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、測試
@RestController
public class TestController {
@Autowired
Data2017Repository 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,還是比較麻煩的。。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM