数据库
母亲
表
+-----------+------+
| 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/