我想通过查询字符串+查询参数来缓存数据库查询的结果。
我正在使用EclipseLink的结果缓存来尝试实现这一目标,但是每次查询都会访问数据库。
注意:我举了一个具有相同注释和逻辑的示例,但删除了所有业务领域术语。
我已打开mysql一般查询日志,并确认每次查询都命中数据库。当我将命名查询更改为仅以1个参数作为主键的查询时,该查询将被缓存。
我尝试在实体上同时使用@Cache和@Cacheable批注,以及不使用Cache批注。
文档指出,使用结果缓存,您不需要主键或索引字段。
@Entity
@Table(name = "Ball")
@XmlRootElement
@Cache
@NamedQueries({
@NamedQuery(name="Ball.findBallWithColor",
query="SELECT b FROM Ball b WHERE b.color = :color",
hints = {
@QueryHint(name=QueryHints.QUERY_RESULTS_CACHE, value = "true"),
@QueryHint(name=QueryHints.QUERY_RESULTS_CACHE_SIZE, value = "10")
}
)})
public class Blue implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private BigInteger ballID
private Color color;
}
public enum Color {
BLUE,
YELLOW,
ORANGE,
RED;
}
创建命名查询并执行它的代码: 在向我们的端点发出1个请求的过程中,多次调用此查询,并且每次查询都会命中数据库。
public List<Ball> findBallsWithColor(Color color) {
TypedQuery<InstitutionLtvCreditScoreGroup> query = em.createNamedQuery("Ball.findBallWithColor", Ball.class);
query.setParameter("color", Color.BLUE);
List<Ball> blueBalls = query.getResultList();
return blueBalls;
}
持久力单位:
<persistence-unit name="Example" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>${some_source}</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<properties>
<property name="eclipselink.weaving.changetracking"
value="false" />
<property name="eclipselink.target-database" value="MySQL" />
<property name="eclipselink.cache.coordination.protocol"
value="fish.payara.persistence.eclipselink.cache.coordination.HazelcastPublishingTransportManager" />
<property name="eclipselink.cache.coordination.channel"
value="myChannel" />
<property name="eclipselink.logging.logger"
value="org.eclipse.persistence.logging.DefaultSessionLog" />
<property name="eclipselink.logging.level" value="WARNING" />
<property name="eclipselink.jdbc.batch-writing" value="JDBC" />
<property name="eclipselink.jdbc.batch-writing.size"
value="1000" />
</properties>
</persistence-unit>
答案 0 :(得分:0)
经过大量测试和阅读规格后,我实际上发现了一些非常微妙的信息,说明为什么缓存不起作用。
JPA 2.2定义了 @Cacheable 批注,该批注可以与persistence.xml文件中的<shared-cache-mode/>
属性一起使用。
我们将其定义如下:<shared-cache-mode>ENABLE_SELECTIVE<shared-cache-mode/>
。这意味着在显式标记为已缓存的实体上启用了缓存。
问题是,在persistence.xml中定义的属性中,我们必须在实体上使用@cacheable批注。 EclipseLink 2.7具有注解扩展(在规范中找不到注解)。其中之一是 @Cache ,它非常相似
因此,<shared-cache-mode>ENABLE_SELECTIVE<shared-cache-mode/>
@Cache
@Entity
class MyEntity {}
将不会被缓存。
@Cacheable(true)
@Entity
class MyEntity{}
将被缓存。
eclipseLink规范说要使用 @Cache 代替JPA的 @Cacheable ,但是我认为这意味着我们不能使用该持久性属性。