I have two tables clients and contact :
public class Contacts implements Serializable{
@Id
@GeneratedValue
private Long idContacts;
private String nomContacts;
private String prenomContacts;
private String telephone;
private String autreTelephone;
private String fax;
private String email;
private int deleted = 0;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "idClient")
private Client client;
}
and I declared an instance of Contact:
Contacts contact = new Contacts()
How can I set the foreign key of Contact manually I tried : contact.getClient().setIdClient(1)
and it did not work.
A major purpose of JPA is to avoid manually fiddling with relationship keys; instead, just use regular Java references. For what you're trying to do:
Client clientOne = clients.find(1L); // or get the client some other way
contact.setClient(clientOne);
Note that Spring Data (in addition to autoimplemented repositories) provides a converter, so that if you have a method argument for your controller that refers to an existing object's ID, you can pass the object itself instead of looking up manually:
@GetMapping("/clients/{id}")
public Client getClient(@PathVariable("id") Client client) {
return client;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.