1
votes

I am new to JPA. I want to comprehed what kind of assistence gives me JPA in persisting objects to database. My example: a Person class is related to an Address class. Each person can have multiple Address es. I model this fact like this:

@Entity
public class Person implements Serializable {
    @Id int id; 
    String firstName;
    @OneToMany(mappedBy="id", cascade={CascadeType.PERSIST, CascadeType.REMOVE})
    List<EMailAddress> emailList;
    //of course i have all my getters

My EmailAddress class is similar:

@Entity 
    public  class EMailAddress implements Serializable {
        @Id @GeneratedValue (strategy=GenerationType.TABLE)
        Integer id;
        String address;
        //here i have all my getters
   }

Ok. The first problem is that when I try to persist a person object with the following, very simple code, I get a foreign key error:

    Person p0 = new Person();
    p0.setFirstName("Alan");
    p0.setId(99);
    //I create an EMailAddress object, and add it to the Person adresses list
    EMailAddress ma = new EMailAddress();
    ma.setAddress("[email protected]");
    p0.setEmailList(new ArrayList());
    p0.getEmailList().add(ma);

    em.getTransaction().begin();
    em.persist(p0);
    em.getTransaction().commit();

The exception:


10924 [main] ERROR org.hibernate.util.JDBCExceptionReporter - INSERT on table 'EMAILADRESS' has caused a violation of foreign key constraint 'FK95CEBD60BE95C400' for key (327680).  The instruction has been rollbacked.

1

1 Answers

2
votes

Your mapping the primary key of the EMailAddress as a foreign key to the Person. Since there is no Person with the id of the EMailAddress (probably 1 as it is @GeneratedValue'ed) you see this exception. Change the mapping on your Person to something like:

@OneToMany(mappedBy="USER_ID", cascade={CascadeType.PERSIST, CascadeType.REMOVE})
List<EMailAddress> emailList;

And it should work. Obviously make sure to update your DB schema if you don't have hibernate create it for you. Add a column USER_ID with a foreign key constraint to Person.ID.