I have read many topics about mapping with JPA + Hibernate, but after trying several things I can not get the expected result.
I have declared all my unidirectional relationships since I do not see the need to bidirect them
My objects to map are: Client has a Country and a list of addresses.
@Table(name = "Client")
@Entity
public class Client
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
private Long id;
@OneToOne(cascade = { CascadeType.MERGE, CascadeType.PERSIST })
@JoinColumn(name="country_id", unique = false, /*nullable = false,*/ insertable = true, updatable = false, foreignKey = @ForeignKey(name = "country_fk0"))
private Country country;
@OneToMany(cascade = { CascadeType.PERSIST }, orphanRemoval = true)
@JoinColumn(name = "address_id",/* nullable = false,*/ foreignKey = @ForeignKey(name = "address_fk0"))
private List<Address> address;
//GETTERS / SETTERS
}
then I will evaluate the client and save it in a new ClientProcessed table, which will reference the Addresses and Country objects stored in my Client Object.
@Table(name = "ProcessedClient")
@Entity
public class ProcessedClient
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
private Long id;
@OneToOne(cascade = { CascadeType.MERGE, CascadeType.PERSIST })
@JoinColumn(name="client_evaluation_id", unique = false, /*nullable = false,*/ insertable = true, updatable = false, foreignKey = @ForeignKey(name = "evaluation_fk0"))
private ClientEvaluation evaluation;
@OneToOne(cascade = { CascadeType.MERGE })
@JoinColumn(name="country_id", unique = false, /*nullable = false,*/, foreignKey = @ForeignKey(name = "country_fk1"))
private Country country;
@OneToMany(cascade = { CascadeType.MERGE}, orphanRemoval = true)
@JoinColumn(name = "address_id",/* nullable = false,*/ foreignKey = @ForeignKey(name = "address_fk2"))
private List<Address> addresses;
//GETTERS / SETTERS
}
So then when i do that:
Country country = new Country();
country.setId(1l); // (DB ID)
// I do the same with addresses
ProcessedClient processedClient = new ProcessedClient();
processedClient.setAddresses(addresses);
processedClient.setCountry(country);
this.getDao().save(processedClient);
Result:
org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing
Thx