Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'dog_id' cannot be null

StackOverflow https://stackoverflow.com/questions/12888301

Question

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?

Was it helpful?

Solution

Add a method in Dog entity class as :

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

Add Cascade as ALL for puppies mapping in Dog.

When you want to save dog with puppy/puppies, you can write something like:

       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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top