6.14. JPA 缓存存储
JPA (Java Persistence API)缓存存储,JpaStore,使用正式模式来持久保留数据。
然后,其他应用程序可以从持久性存储读取,以从 Data Grid 加载数据。但是,其他应用程序不应该与 Data Grid 同时使用持久性存储。
使用 JPA 缓存存储时,您应该考虑以下问题:
- 密钥应为实体的 ID。值应该是实体对象。
-
只允许一个
@Id或@EmbeddedId注释。 -
不支持使用
@GeneratedValue注释自动生成的 ID。 - 所有条目都存储为 immortal。
- JPA 缓存存储不支持分段。
您应该只使用带嵌入式数据网格缓存的 JPA 缓存存储。
JPA 缓存存储配置
XML
<local-cache name="vehicleCache">
<persistence passivation="false">
<jpa-store xmlns="urn:infinispan:config:store:jpa:13.0"
persistence-unit="org.infinispan.persistence.jpa.configurationTest"
entity-class="org.infinispan.persistence.jpa.entity.Vehicle">
/>
</persistence>
</local-cache>
ConfigurationBuilder
Configuration cacheConfig = new ConfigurationBuilder().persistence()
.addStore(JpaStoreConfigurationBuilder.class)
.persistenceUnitName("org.infinispan.loaders.jpa.configurationTest")
.entityClass(User.class)
.build();
配置参数
| 声明性 | programmatic | 描述 |
|---|---|---|
|
|
|
指定 JPA 配置文件 |
|
|
| 指定期望在此缓存中存储的完全限定域名。只允许一个类。 |
6.14.1. JPA 缓存存储示例
这部分提供了使用 JPA 缓存存储的示例。
先决条件
- 配置数据网格以汇总您的 JPA 实体。
流程
在
persistence.xml中定义持久性单元 "myPersistenceUnit"。<persistence-unit name="myPersistenceUnit"> <!-- Persistence configuration goes here. --> </persistence-unit>
创建用户实体类。
@Entity public class User implements Serializable { @Id private String username; private String firstName; private String lastName; ... }使用 JPA 缓存存储配置名为"usersCache"的缓存。
然后,您可以将缓存"usersCache"配置为使用 JPA Cache Store,以便在将数据放置到缓存中时,数据将基于 JPA 配置持久到数据库中。
EmbeddedCacheManager cacheManager = ...; Configuration cacheConfig = new ConfigurationBuilder().persistence() .addStore(JpaStoreConfigurationBuilder.class) .persistenceUnitName("org.infinispan.loaders.jpa.configurationTest") .entityClass(User.class) .build(); cacheManager.defineCache("usersCache", cacheConfig); Cache<String, User> usersCache = cacheManager.getCache("usersCache"); usersCache.put("raytsang", new User(...));使用 JPA 缓存存储的缓存只能存储一种数据类型,如下例所示:
Cache<String, User> usersCache = cacheManager.getCache("myJPACache"); // Cache is configured for the User entity class usersCache.put("username", new User()); // Cannot configure caches to use another entity class with JPA cache stores Cache<Integer, Teacher> teachersCache = cacheManager.getCache("myJPACache"); teachersCache.put(1, new Teacher()); // The put request does not work for the Teacher entity class@EmbeddedId注释允许您使用复合键,如下例所示:@Entity public class Vehicle implements Serializable { @EmbeddedId private VehicleId id; private String color; ... } @Embeddable public class VehicleId implements Serializable { private String state; private String licensePlate; ... }
其他资源