JPA @OneToMany constraint not null
Bonjour,
J'ai un souci lors de la persistance d'une entité avec JPA et Hibernate.
Mon entité Client contient une jointure @OneToMany vers une liste de Contact. Au moment de persister la nouvelle entité Client qui contient des nouveaux Contact, j'obtiens cette erreur :
Citation:
org.postgresql.util.PSQLException: ERREUR: une valeur NULL viole la contrainte NOT NULL de la colonne « client_id »
Mes tables :
Code:
1 2 3 4 5 6 7 8
| CREATE TABLE CLIENT (
id SERIAL,
ref VARCHAR(8) UNIQUE NOT NULL,
lastname VARCHAR(50) NOT NULL,
firstname VARCHAR(50),
...
PRIMARY KEY (id)
); |
Code:
1 2 3 4 5 6 7 8 9
| CREATE TABLE CONTACT (
id SERIAL,
client_id INTEGER NOT NULL,
lastname VARCHAR(50) NOT NULL,
firstname VARCHAR(50),
...
PRIMARY KEY (id),
FOREIGN KEY (client_id) REFERENCES CLIENT (id)
); |
Mes entités :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| @Entity
@Table(name = "client", uniqueConstraints = @UniqueConstraint(columnNames = "ref") )
public class Client {
private Integer id;
private String ref;
private String lastname;
private String firstname;
private Set<Contact> contacts = new HashSet<Contact>(0);
...
@Id
@SequenceGenerator(name = "client_id_seq", sequenceName = "client_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "client_id_seq")
@Column(name = "id", unique = true, nullable = false, updatable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
...
@OneToMany(fetch = FetchType.LAZY, mappedBy = "client", cascade = {CascadeType.ALL})
public Set<Contact> getContacts() {
return this.contacts;
}
public void setContacts(Set<Contact> contacts) {
this.contacts = contacts;
}
} |
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| @Entity
@Table(name = "contact")
public class Contact {
private Integer id;
private Client client;
private String lastname;
private String firstname;
...
@Id
@SequenceGenerator(name = "contact_id_seq", sequenceName = "contact_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "contact_id_seq")
@Column(name = "id", unique = true, nullable = false, updatable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
@JoinColumn(name = "client_id", nullable = false, updatable = false, insertable = true)
public Client getClient() {
return this.client;
}
public void setClient(Client client) {
this.client = client;
}
...
} |
Sauriez-vous comment faire pour que le nouvel id de Client soit définit dans les entités Contact ?
Merci pour votre aide.