0

我有两个具有父子关系的实体。狗显然是父母,小狗是孩子。我如何坚持 Dog-and-puppies 没有错误?

@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
}

基本上,用户将 Dog(带有小狗)作为 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?

4

1 回答 1

3

Dog在实体类中添加一个方法:

    public void addPuppy(Puppy puppy){
           if (this.puppies == null){
               this.puppies = new HashSet<Puppy>();
           }
           puppy.setDog(this); // <--This will set dog as parent in puppy class
           this.puppies.add(puppy);
    }

添加CascadeasALL中的puppies映射Dog

当你想用 保存dogpuppy/puppies,你可以这样写:

       Dog dog = ....getDog object/create new dog object
       Puppy puppy = new Puppy();
       // set puppy attributes.
       dog.addPuppy(puppy);
       //call save method for dog
       dogDao.save(dog);
于 2012-10-15T02:05:33.833 回答