2016-10-14 18 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