If anyone has got cascading persistance working in JPA with database generated primary keys I'd be much obliged if you could let me know how.
Am attempting to use tables with database auto generated primary keys (MySQL AUTO_INCREMENT), and using the JPA cascade features. But I can't see how to make it work.
The problem is that if you cascade persist a series of entities, you need to know the database primary keys before you persist to the database.
If I remove all the cascades in my @entity's, and explicitly persist entities in the correct order so the primary keys are set before them being needed, then all is ok.
When I put the cascades in, my JPA implementation (Toplink) attempts to create the entities with foreign keys to tables with the yet to be generated primary keys all null. I was hoping JPA/Toplink would be clever enough to persist the entities in order, setting the database generated primary keys as it went.
Has anyone tried this in Hibernate?
Sampe code exerts that does not work:
@Entity
public class Address implements Serializable {
private long id;
private Collection<Contact> contacts = new ArrayList<Contact>();
...
@OneToMany(cascade = { CascadeType.ALL })
public Collection<Contact> getContacts() {
return contacts;
}
...
}
@Entity
public class Contact implements Serializable {
private long id;
...
@Id
@Column(updatable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long getId() {
return this.id;
}
...
}
CREATE TABLE address (
id BIGINT NOT NULL AUTO_INCREMENT
, address_line_1 VARCHAR(64)
, address_line_2 VARCHAR(64)
, address_line_3 VARCHAR(64)
, suburb VARCHAR(64)
, postcode VARCHAR(16)
, state VARCHAR(64)
, country_code CHAR(2)
, PRIMARY KEY (id)
);
CREATE TABLE contact (
id BIGINT NOT NULL AUTO_INCREMENT
, address_id BIGINT
, contact_type CHAR(10)
, value VARCHAR(255)
, PRIMARY KEY (id)
, INDEX (address_id)
, CONSTRAINT FK_contact_address FOREIGN KEY (address_id)
REFERENCES address (id)
);