Reputation: 9141
I have a very simple use case where I have 2 entities : Client and Email (where a Client has OneToMany Emails).
When I try to save an email alone, it works with no error, and I can see it in database afterwards :
@Test
public void insertEmail() {
Client fetchedClient = clientRepository.findClientsFullByPdlClient("25492040401007");
Email email = new Email();
email.setClient(fetchedClient);
email.setEmail("[email protected]");
emailRepository.save(email);
}
But when I try my main use case, which is saving a new client with its emails using cascade, I get an error :
The test case :
@Test
public void testCreateClient() {
Client client = new Client();
client.setPdlClient(PDL_CLIENT_TO_CREATE);
Email email1 = new Email();
email1.setEmail("[email protected]");
email1.setOrdre((short) 1);
client.addEmail(email1);
Email email2 = new Email();
email2.setEmail("[email protected]");
email2.setOrdre((short) 2);
client.addEmail(email2);
clientRepository.save(client);
}
The error :
WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 1048, SQLState: 23000
ERROR o.h.e.jdbc.spi.SqlExceptionHelper - Column 'EMAIL' cannot be null
Relevant parts from Client (generated by Dali + EclipseLink tools) :
//bi-directional many-to-one association to Email
@OneToMany(cascade = CascadeType.ALL, mappedBy="client")
private List<Email> emails = new ArrayList<Email>();
public Email addEmail(Email email) {
getEmails().add(email);
email.setClient(this);
return email;
}
Email.java (no getters/setters) :
@Entity
@Table(name="EMAIL")
public class Email {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID_EMAIL")
private Integer idEmail;
@Column(name="EMAIL")
private String email;
//bi-directional many-to-one association to Client
@ManyToOne
@JoinColumn(name="ID_CLIENT")
private Client client;
}
Now if I try my cascade save right after my successful single email insertion shown above, I get a different error, showing my "email" property is set and readable !
ERROR o.h.e.jdbc.spi.SqlExceptionHelper - Duplicate entry '[email protected]' for key 'AK_EMAIL'
So I'm a bit confused. What am I doing wrong ? If it was complaining about the absence of ID_CLIENT, I would understand, but this " 'EMAIL' cannot be null ", what is it about ?
Upvotes: 1
Views: 297
Reputation: 9141
Ok, my bad, all the code above is actually working.
I had a typo :
Email email2 = new Email();
email.setEmail("[email protected]");
email.setOrdre((short) 2);
client.addEmail(email2);
instead of :
Email email2 = new Email();
email2.setEmail("[email protected]");
email2.setOrdre((short) 2);
client.addEmail(email2);
I could delete this question, but maybe it can be a useful working example for other people.
Upvotes: 1