在日常开发中,如果使用hibernate的话,常常会被hibernate的事务搞得焦头烂额。今天解决了之前项目中一直存在的问题,记录一下。
有一张表TemplateCopy,如下
public class TemplateCopy {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String description;
@OneToMany(mappedBy = "template")
private Set<SubDomainWeightsCopy> subDomainWeights;
@OneToMany(mappedBy = "template")
private Set<QuestionWeightsCopy> questionWeights;
}
关联了两张表:
public class SubDomainWeightsCopy {
@JsonIgnore
@Id
@ManyToOne
@JoinColumn(name = "template_id")
private TemplateCopy template;
@Id
@ManyToOne
@JoinColumn(name = "sub_domain_id")
private SubDomainCopy subDomain;
private BigDecimal weights; //权重
private BigDecimal score;
@Data
public static class RelationId implements Serializable {
private Integer template;
private Integer subDomain;
}
}
public class QuestionWeightsCopy implements IWeightsValue {
@JsonIgnore
@Id
@ManyToOne
@JoinColumn(name = "template_id")
private TemplateCopy template;
@Id
@ManyToOne
@JoinColumn(name = "question_id")
private QuestionCopy question;
private BigDecimal weights;
private BigDecimal score;
@Data
public static class RelationId implements Serializable {
private Integer template;
private Integer question;
}
}
简单的看一下,TemplateCopy中有一堆SubDomainWeightsCopy,和一堆QuestionWeightsCopy,我们在保存TemplateCopy的时候,通常按照如下来保存
1. templateCopy = save(TemplateCopy)
2. QuestionWeightsCopy.setTemplateCopy(templateCopy)
3. save(QuestionWeightsCopy)
4. SubDomainWeightsCopy.setTemplateCopy(templateCopy)
5. save(SubDomainWeightsCopy)
到这就好了,数据库已经保存了关联关系。但是,这时候如果返回save好的templateCopy,subDomainWeights和questionWeights将会是null。
EntityManager clear方法会清空其关联的缓存,从而强制在事务中稍后执行新的数据库查询。
原文:https://www.cnblogs.com/gcdd/p/12292062.html