Reputation: 1467
I tried searching for this specific issue but could not get any help
While creating Employee --> Account should get created.
My entities are --> Employee entity
@Entity
@Table(name = "EMPLOYEE")
public class EMPLOYEE implements Serializable {
private static final long serialVersionUID = -1798070786993154676L;
@Id
@Column(name = "EMPLOYEE_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private int EMPLOYEE_id;
@Column(name = "EMPLOYEE_name")
private String EMPLOYEE_name;
@Column(name = "EMPLOYEE_desc")
private String EMPLOYEE_desc;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "EMPLOYEE_id")
@MapsId
private ACCOUNT account;
// getters and setters
}
account entity -->
@Entity
@Table(name = "ACCOUNT")
public class ACCOUNT implements Serializable {
private static final long serialVersionUID = -6790693372846798580L;
@OneToOne( fetch = FetchType.LAZY)
@JoinColumn(name = "EMPLOYEE_id")
private EMPLOYEE employee
@Id
@Column(name = "account_id")
private int account_id;
@Column(name = "account_desc")
private String account_desc;
// getters setters
}
While creating Employee --> Account should get created.
My pojo is getting mapped correctly as shown below -->
employee = { EMPLOYEE_id = 0 ,
EMPLOYEE_name = 'abc' ,
EMPLOYEE_desc = 'new employee' ,
account = { account_id = 1 ,
account_desc = 'my account' ,
EMPLOYEE_id = 0 }
}
so when i same employee object - it generates employee_id , but the same employee_id is not getting populated in account table
It is partly working --> in the Account table Employee_id is not getting populated.
I tried searching so many questions on stackOverflw - but no luck so far. Any help is appreciated.
Thank you in advance
Upvotes: 1
Views: 503
Reputation: 740
If the @OneToOne is defined on both sides of the relationship, one side should be the owner. That is the entity that has the foreign key. The other side should have the mappedBy attribute. So the following works for me
@Entity
@Table(name = "EMPLOYEE")
public class EMPLOYEE implements Serializable {
@OneToOne(cascade= CascadeType.ALL, mappedBy = "employee") // non-owner side
private Account account;
....
}
@Entity
@Table(name = "ACCOUNT")
public class Account implements Serializable {
@OneToOne( fetch = FetchType.LAZY)
@JoinColumn(name = "EMPLOYEE_id") // owner-side
private Employee employee;
}
Upvotes: 0