【问题标题】:How to cache an object with a key which is not owned by the object, using ehcache?如何使用 ehcache 使用不属于对象的键来缓存对象?
【发布时间】:2023-04-08 19:30:01
【问题描述】:

我对 ehcache 相当陌生,据我所知,在方法级别上,缓存正在处理要缓存的对象的 id。但是我有不同的情况。

我有一个用户类和一个角色类,它们之间的关系是多对多的,并通过 ids 存储在另一个表中。

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;

    ...

}

顺便提一下,没有这样的 UserRole 域类。

服务方法有点像;

public RoleService{

    @Cacheable
    public Set<Role> getUserRoles(Long userId)
    {
        ...
    }
}

问题是,在服务级别上,我希望根据 userId 缓存角色。如何使用用户 id 缓存角色?

【问题讨论】:

    标签: java hibernate ehcache second-level-cache


    【解决方案1】:

    如果您将 ehcache 用于 spring 的方法缓存,它应该可以开箱即用。

    <ehcache:annotation-driven cache-manager="ehCacheManager" />
    
    @Cacheable(name="getUserRoles", key="userId")
    

    Ehcache Spring documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 2017-09-15
      • 2016-03-29
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 2015-09-01
      相关资源
      最近更新 更多