I am trying to implement a one-to-one mapping and below is the entities involved:
UserID which acts as composite primary key:
@Embeddable
public class UserID implements Serializable {
private static final long serialVersionUID = 1L;
private int ssnID;
// getters and setters...
}
Vehicle Entity:
@Entity
public class Vehicle {
@Id
private int vehicleID;
private String description;
// getters and setters..
}
UserInfo entity which has UserID as composite primary key and having one-to-one relationship with Vehicle Entity:
@Entity
public class UserInfo {
@EmbeddedId
UserID userID; // Object which acts as a primary key (composite primary key)
private String full_name;
@OneToOne
@JoinColumn(name="VEHICLE_ID")
Vehicle veh;
// Getters and Setters...
}
UserInfo
is the owning-side entity as it has the FK
(using @JoinColumn) and has UserID
as composite primary key.
When I save the UserInfo
object, the below are the sql logs of the hibernate:
Hibernate: drop table UserInfo if exists
Hibernate: drop table Vehicle if exists
Hibernate: create table UserInfo (ssnID integer not null, full_name varchar(255), VEHICLE_ID integer, primary key (ssnID))
Hibernate: create table Vehicle (vehicleID integer not null, description varchar(255), primary key (vehicleID))
Hibernate: alter table UserInfo add constraint FK9nx05ha53jhcue5rwks77x0mv foreign key (VEHICLE_ID) references Vehicle
After this, it throws the exception:
ERROR: Referential integrity constraint violation: "FK9NX05HA53JHCUE5RWKS77X0MV: PUBLIC.USERINFO FOREIGN KEY(VEHICLE_ID) REFERENCES PUBLIC.VEHICLE(VEHICLEID) (100)"; SQL statement:
update UserInfo set full_name=?, VEHICLE_ID=? where ssnID=? [23506-190]
Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK9NX05HA53JHCUE5RWKS77X0MV: PUBLIC.USERINFO FOREIGN KEY(VEHICLE_ID)
REFERENCES PUBLIC.VEHICLE(VEHICLEID) (100)"; SQL statement:
update UserInfo set full_name=?, VEHICLE_ID=? where ssnID=? [23506-190]
I am not able to understand why this is throwing the exception; I am not inserting any duplicate values.
Is there any issues in my mapping using @OneToOne or @JoinColumn?
Can anyone help me understand this?
EDIT:
I have created a helper class which does the actual saving, part of the snippet is:
public void saveUser(UserInfo userInfo) {
Session session = null;
session = sf.openSession();
session.beginTransaction();
session.save(userInfo);
session.getTransaction().commit();
session.close();
}
So, from main() I call this helper method, and save the Entity UserInfo
(which has the other entity Vehicle
set).
Please note I am not saving the Vehicle
entity, does it need to be saved explicit?