[英]How to cache an object with a key which is not owned by the object, using ehcache?
I am fairly new to ehcache and as far as I know on method level the cacheing is working on the id of object to be cached. 我对ehcache相当陌生,据我所知,在方法级别,缓存正在处理要缓存的对象的ID。 However I have a different situation. 但是我有不同的情况。
I have a User class and a role class, the relation between them is many-to-many and stored in another table by ids. 我有一个User类和一个Role类,它们之间的关系是多对多的,并通过id存储在另一个表中。
public class User{
@Id
@Column(name="ID")
@GeneratedValue(generator="idGenerator",strategy = GenerationType.SEQUENCE)
private Long id;
...
@ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER)
@JoinTable(name = "ROLE", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
protected Set<Role> roles;
...
}
public class Role{
@Id
@Column(name="ID")
@GeneratedValue(generator="idGenerator",strategy = GenerationType.SEQUENCE)
private Long id;
...
@ManyToMany(targetEntity = User.class)
@JoinTable(name = "USER", joinColumns = { @JoinColumn(name = "ROLE_ID") }, inverseJoinColumns = { @JoinColumn(name = "USER_ID") })
protected Set<Role> roles;
...
}
Just to mention, there no such a UserRole domain class. 仅需提及,没有这样的UserRole域类。
And the service method is somethig like; 而且服务方法有点像;
public RoleService{
@Cacheable
public Set<Role> getUserRoles(Long userId)
{
...
}
}
The thing is that on the service level I want the roles to be cached per userId basis. 问题是,在服务级别上,我希望每个userId都缓存角色。 How can I cache roles using id of the user? 如何使用用户ID缓存角色?
If you use ehcache for method caching with spring it should work out of the box. 如果您将ehcache用于spring的方法缓存,则应该可以立即使用。
<ehcache:annotation-driven cache-manager="ehCacheManager" />
@Cacheable(name="getUserRoles", key="userId")
See Ehcache Spring documentation . 请参阅Ehcache Spring文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.