Hibernate二级缓存一对一不起作用

时间:2016-10-14 01:07:15

标签: java hibernate spring-data-jpa

我使用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);

1 个答案:

答案 0 :(得分:4)

对于ToOne关联实体的@ManyToOne个关联only the id (foreign key)缓存在拥有实例的条目中:

  

Hibernate以缓冲形式存储缓存的实体,即   类似于数据库表示。除了外键   @OneToOneDetails子项的列值   关联,实体关系不存储在缓存中。

因此,当从L2缓存组装拥有实例时,必须通过其id加载关联实体。为避免这种情况,请将关联实体(在您的情况下为val newstructtype = StructType(existing_df.schema.map( x => { if (x.name == "fieldname_to_change") StructField("new_fieldname",TimestampType,true) else x}) )设置为可缓存。

还提供了更多详细信息herehere