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.