Eclipselink在线程之间共享缓存

时间:2012-12-14 00:43:14

标签: java-ee jpa jpa-2.0 eclipselink

这是我的配置,第一个persistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0">     
<persistence-unit name="db" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <!-- This is needed to allow it to find entities by annotations -->
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <shared-cache-mode>ALL</shared-cache-mode> 

    <properties>
    <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="javax.persistence.jdbc.user" value="user"/>
        <property name="javax.persistence.jdbc.password" value="password"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://ip/dbname"/>

        <property name="eclipselink.logging.level" value="FINEST"/>     
        <property name="eclipselink.weaving" value="static"/>
        <property name="eclipselink.cache.type.default" value="SoftWeak"/>

    </properties>
</persistence-unit>
</persistence>

以下是我创建EntityManagerFactory的方法。

private static EntityManagerFactory factory = null;

public synchronized static DBStore getInstance() {
    if (factory == null) {
        factory = Persistence.createEntityManagerFactory("db");
    }
    return new DBStore(factory.createEntityManager());
}

其中DBStore是我用作访问EntityManager的中间人的对象。

使用EclipseLink 2.4

这就是问题所在。如果我创建线程1,为它获取一个DBStore对象,对现有实体进行一些更改,将它们提交到数据库,并且我有另一个并发线程(2)在更改生成和提交之前和之后加载该实体,第二个线程没有看到第一个线程提交的更改。我知道更改是在数据库中,因为我可以看到它们。此外,如果在第二个线程上我在检查实体的值之前调用EntityManager.refresh(实体),那么它工作正常。所以我的猜测是我的两个线程没有相互共享它们的缓存,即使EclipseLink应该这样做,如果你使用相同的EntityManagerFactory,我认为它是静态的。

那我的设置有什么问题?

1 个答案:

答案 0 :(得分:0)

每个EntityManager都有自己的缓存,因为它们用于表示单独的事务上下文。因此,读入EntityManager的预先存在的实体将不会显示其他实体的更改,除非刷新或清除EM并重新读取实体。关于JPA的Eclipselink缓存在此处描述:http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching

相关问题