1

数据库

mother桌子

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

child桌子

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

妈妈.java

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

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

}

子.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();

}

会议

应用程序上下文.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 重置一个域与其他域可能存在的一对多关系的缓存?

4

1 回答 1

1

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

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);
}
于 2013-01-10T18:01:05.810 回答