我正在使用Hibernate和Spring / Spring MVC。 我有两个实体,AccommodationRequest和Restriction。 这种关系是AccommodationRequest可以有很多限制。
当我使用限制保存AccommodationRequest时,两个结果都会保存到数据库中 但限制缺少外键/连接列(accommodationRequestId)。 我相信我必须缺少一些东西。任何帮助表示赞赏。
AccommodationRequest的定义是:
@Entity
public class AccommodationRequest {
....
@OneToMany(mappedBy="accommodationRequest",
targetEntity=Restriction.class,
fetch=FetchType.EAGER,
cascade=CascadeType.ALL)
private List<Restriction> restrictions;
public List<Restriction> getRestrictions(){
return restrictions;
}
public void setRestrictions(List<Restriction> restrictions){
this.restrictions = restrictions;
}
....
定义限制:
@Entity
public class Restriction {
@Id
@GeneratedValue
private long id;
private String restriction;
@ManyToOne
@JoinColumn(name="accommodationRequestId")
private AccommodationRequest accommodationRequest;
public AccommodationRequest getAccommodationRequest() {
return accommodationRequest;
}
public void setAccommodationRequest(AccommodationRequest accommodationRequest) {
this.accommodationRequest = accommodationRequest;
}
以下是执行保存的代码:
Restriction restriction = new Restriction();
restriction.setRestriction("test restrcition 6");
List<Restriction> restrictions = new ArrayList<Restriction>();
restrictions.add(restriction);
long id = accommodationService.saveOrUpdate(accommodationRequest);
accommodationRequest.setRestrictions(restrictions);
accommodationService.saveOrUpdate(accommodationRequest);
答案 0 :(得分:1)
您尚未将AccommodationRequest设置为限制。
Restriction restriction = new Restriction();
restriction.setRestriction("test restrcition 6");
restriction.setAccommodationRequest(accommodationRequest); // You have to do this
List<Restriction> restrictions = new ArrayList<Restriction>();
restrictions.add(restriction);
long id = accommodationService.saveOrUpdate(accommodationRequest);
accommodationRequest.setRestrictions(restrictions);
accommodationService.saveOrUpdate(accommodationRequest);