2016-10-14 70 views
2

我使用Ehcache提供程序來提供Hibernate二級緩存。它緩存一個一對多的集合,與@Cache註釋,但不緩存一到一個:休眠二級緩存一對一不起作用

//hb annotations 
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "user") 
public class User { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Integer id; 

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user") 
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "details") 
    private Details details; 

    //getters, setters, constructors etc. 

} 

//hb annotations 
public class Details { 

    @GenericGenerator(name = "generator", strategy = "foreign", 
    parameters = @Parameter(name = "property", value = "user")) 
    @Id 
    @GeneratedValue(generator = "generator") 
    @Column(unique = true, nullable = false) 
    private Integer id; 

    @OneToOne 
    @PrimaryKeyJoinColumn 
    private User user; 

    //getters, setters, constructors ets. 

} 

我使用Spring JpaRepository獲取數據:

userRepository.findOne(id); 

回答

3

對於ToOne協會only the id (foreign key)的關聯實體實例緩存在擁有實例的條目中:

Hibernate存儲脫水形式的緩存實體,即 類似於數據庫表示。除了@ManyToOne@OneToOne子端 關聯的外鍵 列值之外,實體關係不會存儲在緩存中。

因此,當擁有實例從L2緩存中組裝完成時,相關實體必須通過它的id加載。爲了避免這種情況,請將關聯的實體(您的案例中的Details)也可以緩存。

更多可用的細節還有herehere