0
我有兩個具有父子關係的實體。狗明顯是父母,小狗是孩子。我如何堅持小狗和小狗沒有錯誤?異常:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列'dog_id'不能爲空
@XmlRootElement(name = "dog")
@Entity
@Table(name = "dog", catalog = "zoo")
public class Dog{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "dogname")
private String dogName;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "Dog")
private Set<Puppy> puppies;
...// getters and setters
@XmlElementWrapper(name = "puppies")
@XmlElement(name = "puppy")
public Set<Puppy> getPuppy() {
return this.puppies;
}
}
@Entity
@Table(name = "puppy", catalog = "zoo")
public class Puppy{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "puppyname")
private String puppyName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "dog_id", nullable = false)
private Dog dog;
...// getters and setters
}
基本上,用戶通過狗 - 它是小狗 - 作爲jaxbElement。
@POST
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response createDog(JAXBElement<Dog> jaxbDog) {
Dog dog = jaxbDog.getValue();
dogDao.save(dog);
return Response.status(Response.Status.OK).build();
}
我的問題又是如何讓小狗看到母狗的dog_id?
通過'addPuppy(小狗小狗)'你除了'setPuppy(小狗小狗)表示'。我已經有了二傳手和得分手。 – kasavbere
還有什麼意思是'爲Dog中的小狗映射添加級聯作爲ALL'。我不是已經有了嗎?請澄清。您可以將我的代碼複製到您的回覆中,並將其編輯爲正確的版本。謝謝。 – kasavbere
編號'setPuppy'以'Set'作爲參數。我在說新的方法,我在答案中提到過。在你的Dog類中添加'addPuppy'方法,然後使用這種方法一次給狗添加一隻小狗。如果你想使用'setPuppy',那麼更新該方法來迭代小狗,並在每隻小狗中設置'狗即這個'。 –