java - 如何让EhCache重置一个域与其他域之间的一对多关系的缓存?

标签 java spring hibernate one-to-many ehcache

数据库

母亲

+-----------+------+
| mother_id | name |
+-----------+------+
|         1 | m1   |
|         2 | m2   |
+-----------+------+

子表

+----------+-----------+------+
| child_id | mother_id | name |
+----------+-----------+------+
|        1 |         1 | c1   |
|        2 |         1 | c2   |
|        3 |         2 | c3   |
+----------+-----------+------+

域名

Mother.java

@Entity
@Table(name = "mother")
public class Mother {

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "mother")
    public List<Child> getChilds() {
        return this.childs;
    }

}

Child.java

@Entity
@Table(name = "child")
public class Child {

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "id_mother", nullable = false)
    public Mother getMother() {
        return this.mother;
    }

}

MotherDao.java

public interface MotherDao {

    @Cacheable(cacheName = "dao")
    public List<Mother> findAll();

    @TriggersRemove(cacheName = "dao")
    public void delete(Integer pk);

}

MotherDao.java

public interface ChildDao {

    @Cacheable(cacheName = "dao")
    public List<Child> findAll();

}

session

applicationContext.xml

<ehcache:annotation-driven cache-manager="ehCacheManager" />    
<bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" />

ehcache.xml

<cache name="dao"
    eternal="false"
    maxElementsInMemory="10000"
    overflowToDisk="false"
    timeToIdleSeconds="86400"
    imeToLiveSeconds="86400"
    memoryStoreEvictionPolicy="LFU" />

问题

System.out.println(motherDao.findAll().size());
System.out.println(childDao.findAll().size());
motherDao.delete(1);
System.out.println(motherDao.findAll().size());
System.out.println(childDao.findAll().size());

打印:

2
3
1
3

而不是:

2
3
1
1

由于删除了母级,级联删除了两个子级,但之前的 childDao.findAll() 缓存了其结果。

问题

如何让EhCache重置域与其他域之间的一对多关系的缓存?

最佳答案

您可以为此使用两个缓存。下面是一个例子。

public interface ChildDao {

    @Cacheable(cacheName = "childDao")
    public List<Child> findAll();

}

道妈妈。

public interface MotherDao {
    @Cacheable(cacheName = "motherDao")
    public List<Mother> findAll();

    @TriggersRemove(cacheName={"motherDao", "childDao"})
    public void delete(Integer pk);
}

关于java - 如何让EhCache重置一个域与其他域之间的一对多关系的缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14263439/

相关文章:

java - 无法在 IntelliJ 上为我的 Maven 项目使用 lagom

spring - Spring 3.1 Junit测试中获取WebApplicationContext

java - 集合在 Java 中是最终的是什么意思?

java - spring Autowiring (属性名和bean名必须相同)

java - 在 Java 中将多个 ArrayList 保存/加载到一个文件中

java - Logback 日志由应用程序保持打开状态,不会从磁盘中删除

java - 将文件内容读入类对象

java - 无法猜测 Search 5.5 中的 FieldBridge。未索引的字段

java - 如何在服务器上存储图像,以便可以将带有 id 的图像路径作为 map 存储在属性文件中,以便我们可以根据 id 获取图像

hibernate - JPA + Hibernate 扩展表映射