SpringBoot-JPA 支持分表
2018-01-23 17:05
671 查看
摘要: JPA Entity对象分表映射的一种方案
简介
- JPA Entity对象继承,通过@Inheritance配置,有三种方式SINGLE_TABLE、TABLE_PER_CLASS、JOINED,这里不作赘述。 - Entity对象的分库分表操作 - 分库,为了管理DB的连接数,建议通过入口的分流,将不同DB的数据分流到不同的应用; - 分表,这是本文关注的主要问题,目标是调用JPA时不需要关心是否分表以及映射的规则,即分表对于Entity操作层是透明的;主要的步骤如下: - 对象声明 - 实现JPA interceptor 拦截器 - 加载拦截器
对象声明
- 数据对象的基类,引入了@MappedSuperclass,如下面的样例
@MappedSuperclass class UserBase { @Id private Long id; private String name; private int age; ... ... }
- 数据对象,继承基类,使用[@Entity](https://my.oschina.net/u/1260961),如下面的样例
//模板表,用于JPA代码编写 @Entity @Table(name = "t_user") public class User extends UserBase { ... ...}
//id是0或者偶数的数据分表,用于配置了hibernate.ddl-auto时维护库表结构,不会出现在JPA相关代码中 @Entity @Table(name = "t_user_0") public class User0 extends UserBase { ... ...}
//与User0对应,id是奇数的数据分表 @Entity @Table(name = "t_user_1") public class User1 extends UserBase { ... ...}
// 数据对象操作类声明 public interface UserDao extends CrudRepository<User, Long> {}
JPA interceptor 拦截器
- 声明
import org.hibernate.EmptyInterceptor; public class MyInterceptor extends EmptyInterceptor {
- 推荐使用ThreadLocal缓存业务对象类型和ID
static class Cached { Class<?> clazz; Serializable id; Cached(Class<?> clazz, Serializable id) { super(); this.clazz = clazz; this.id = id; } ... ... //自动生成的hashCode、equals方法 }
- 重载如下的方法onLoad、onSave、getEntity,调用ThreadLocal.set - 重载onPrepareStatement方法,示意代码如下
Cached id = threadLocal.get(); threadLocal.remove(); if(id == null) { return sql; } if(id.clazz == User.class) { long offset = ((Long)id.id).longValue() / 2; return sql.replace("t_user", "t_user_" + offset); }
加载拦截器 Application.yml
spring: jpa: properties: hibernate: ejb: interceptor: [拦截器类名]
相关文章推荐
- SpringBoot学习-支持JPA
- 4. Spring Boot 1.2.5,Spring Data JPA多数据源支持
- SpringBoot系列(四)SpringBoot 之 Spring Data Jpa 支持
- springboot- jpa mysql支持 每天进步百分之一
- spring boot springjpa 支持多个数据源的实例代码
- SpringCloud SpringBoot mybatis 分布式微服务(十一)Spring Boot多数据源配置与使用(Spring-data-jpa支持)
- springboot springjpa 支持多个数据源
- SpringBoot持久层支持-springboot中如何运用JPA,简单例子
- 代码生成器CodeGenerator(目前只支持SpringBoot/SpringDataJpa)
- SpringBoot application.yml logback.xml,多环境配置,支持 java -jar --spring.profiles.active(转)
- springboot使用JPA时间类型进行模糊查询的方法
- springboot之web项目开发(spring+jpa+jsp)
- Spring Boot + Jpa(Hibernate) 架构基本配置
- springboot+springdatajpa 数据库命名
- Spring Boot+JPA+Mysql+ThymeLeaf快速构建CURD系统(一)Spring Boot介绍
- Spring Boot+JPA+Mysql+ThymeLeaf快速构建CURD系统(二)搭建SpringBoot工程
- Spring Boot+JPA+Mysql+ThymeLeaf快速构建CURD系统(一)Spring Boot介绍
- springboot jpa Query使用原生SQL例子--测试通过
- 在Spring Boot中使用Spring-data-jpa实现分页查询
- Java 9 和Spring Boot 2.0纷纷宣布支持的HTTP/2到底是什么?