例外:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:Column' dog_id'不能为空

时间:2012-10-15 01:47:01

标签: java mysql hibernate jaxbelement

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

@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();
}

我的问题是,我如何让小狗看到母狗的狗狗?

1 个答案:

答案 0 :(得分: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);
    }

Cascade ALL添加为puppies Dog中的dog映射。

如果您要puppy/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); ,可以写下以下内容:

{{1}}