Hello,
I have a mapping problem with the following scenario. I'm not sure how I would configure the mapping.
This is the class "Customer" as the "main table", it does not have any foreign key:
Code:
@Entity
@Table( name = "customer" )
public class Customer
{
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Integer id;
@OneToOne( mappedBy = "customer", cascade = CascadeType.ALL )
private Location homeLocation;
@OneToOne( mappedBy = "customer", cascade = CascadeType.ALL )
private Location workLocation;
// Getters and setters
// ....
}
The following class decribes a second table:
Code:
@Entity
@Table( name = "location" )
public class Location
{
public enum LocationType {
HOME, WORK
}
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY )
private Integer id;
@ManyToOne( optional = true )
@JoinColumn( name = "customer_id" )
private Customer customer;
private LocationType locationType;
prviate String someOtherData;
// Getters and setters
// ....
}
(This example is a simplified version of my DB schema/domain model, but it reflects the current situation.)
You can see that one Customer can have two locations (home and work). The following code shows how to construct a Customer object, ready for persistence:
Code:
Location homeLocation = new Location();
homeLocation.setLocationType( LocationType.HOME );
Location workLocation = new Location();
workLocation.setLocationType( LocationType.WORK );
Customer customer = new Customer();
customer.setHomeLocation( homeLocation );
customer.setWorkLocation( workLocation );
homeLocation.setCustomer( customer );
workLocation.setCustomer( customer );
Now I have a "customer" object which I can save to the database via Hibernate without problems. But, I am not able to load such an object from the database. The load process throws the following exception:
Code:
org.hibernate.HibernateException: More than one row with the given identifier was found: 9, for class: de.foo.domain.Customer
The explanation is (so I think), that we have two rows in the Location table, each with a foreign key pointing to the same Customer row. When the join occurs, it finds two Location rows but only one was expected.
What I want is, that the property "homeLocation" of class "Customer" is mapped to the row with the appropriate foreign key for it's customer AND with the column "locationType" with value "HOME". The property "workLocation" should be mapped to the row which column "locationType" has a value of "WORK".
How do I configure such a mapping? Can I tell Hibernate to use the "locationType" column for further identification to decide, which property of the Customer class it must set?
I really appreciate any help you can offer
Thanks a lot!