I have two entities with a parent-child relationship. Dog is the parent obviously and the Puppy is the child. How do I persist Dog-and-puppies without error?
@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
}
Basically a user passes in a Dog -- with it's puppies -- as a 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();
}
My question, again, is how do I get the puppies to see the dog_id of the parent dog?
Add a method in
Dog
entity class as :Add
Cascade
asALL
forpuppies
mapping inDog
.When you want to save
dog
withpuppy/puppies
, you can write something like: