I am trying to understand OneToOne mapping between two Entities.
I am not able to understand how to specify the mappedBy
attribute in OneToOne
for making it bi-directional relation.
UserID embeddable type:
@Embeddable
public class UserID implements Serializable {
private static final long serialVersionUID = 1L;
private int ssnID;
private int uniqueNum;
// getters and setters..
}
VehicleID embeddable type:
@Embeddable
public class VehicleID implements Serializable {
private int vehicleID;
private int regNum;
// getters and setters
}
Vehicle Entity having composite primary key VehicleID:
@Entity
public class Vehicle {
@EmbeddedId
private VehicleID vehicleID;
private String description;
// getters and setters..
}
UserInfo Entity having composite priamary key UserID and is owning-side entity for OneToOne relationship between UserInfo and Vehicle:
@Entity
public class UserInfo {
private String full_name;
@EmbeddedId
UserID userID;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumns({@JoinColumn(name="vehicle_ID") , @JoinColumn(name="reg_Num")}) // Composite primary key in Vehicle
Vehicle veh;
// getters, setters and other code
}
UserInfo
is the owning-side entity and having OneToOne
relationship with Vehicle
entity (which has composite VehicleID as primary key).
My doubt is here:
In UserInfo
entity, we specify the OneToOne
relationship (and the annotations):
@OneToOne(cascade=CascadeType.ALL)
@JoinColumns({@JoinColumn(name="vehicle_ID") , @JoinColumn(name="reg_Num")})
Vehicle veh;
As can be seen above that in UserInfo
table, we are having a composite foreign key on Vehicle
table, and name of the JoinColumn
specifying as vehicle_ID
and reg_Num
.
Now, when I want to make it bi-directional relation we need to use the mappedBy
attribute, and it is that where I am not able to understand what property to refer.
@Ent/ity
public class Vehicle {
@EmbeddedId
private VehicleID vehicleID;
private String description;
@OneToOne(mappedBy="UserID")
private UserInfo userInfo;
// getters and setters..
}
I kept "UserID" as it is "composite" primary key for UserInfo, but it is throwing exception:
Exception in thread "main" org.hibernate.AnnotationException: Unknown mappedBy in: com.example.entity.Vehicle.userInfo, referenced property unknown: com.example.entity.UserInfo.UserID
I am not able to understand what property to refer here; the examples which i have seen in tutorials, most of them have a single PK, FK; but in my case it is composite PK, FK.
Can anyone help me understand this?