簡體   English   中英

如何使用ehcache使用對象不擁有的鍵來緩存對象?

[英]How to cache an object with a key which is not owned by the object, using ehcache?

我對ehcache相當陌生,據我所知,在方法級別,緩存正在處理要緩存的對象的ID。 但是我有不同的情況。

我有一個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;

    ...

}

僅需提及,沒有這樣的UserRole域類。

而且服務方法有點像;

public RoleService{

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

問題是,在服務級別上,我希望每個userId都緩存角色。 如何使用用戶ID緩存角色?

如果您將ehcache用於spring的方法緩存,則應該可以立即使用。

<ehcache:annotation-driven cache-manager="ehCacheManager" />

@Cacheable(name="getUserRoles", key="userId")

請參閱Ehcache Spring文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM