【问题标题】:Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'dog_id' cannot be null异常:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列“dog_id”不能为空
【发布时间】:2012-10-15 01:47:00
【问题描述】:

我有两个具有父子关系的实体。狗显然是父母,小狗是孩子。如何无误地坚持 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?

【问题讨论】:

    标签: java mysql hibernate jaxbelement


    【解决方案1】:

    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 以在Dog 中映射puppies

    当你想用puppy/puppies 保存dog 时,你可以这样写:

           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);
    

    【讨论】:

    • addPuppy(Puppy puppy) 的意思是除了setPuppy(Puppy puppy)。我已经有了 setter 和 getter。
    • 还有Add Cascade as ALL for puppies mapping in Dog是什么意思。我不是已经有了吗?请澄清。您可以将我的代码复制到您的回复中并将其编辑为正确的版本。谢谢。
    • 没有。 setPuppySet 作为参数。我在谈论新方法,我在答案中提到过。在Dog 类中添加方法addPuppy,然后使用此方法一次向狗添加一只小狗。如果您想使用setPuppy,请更新该方法以迭代小狗并在每只小狗中设置dog i.e. this
    猜你喜欢
    • 2013-12-02
    • 2015-12-22
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多