Reputation: 5398
I have two tables I need to insert in to in Hibernate - I have a User and every user belongs is a Member. Therfore when creating a new user I need a new entry in the Member table. I have attempted this via creating a Member object which maps to my member table and then having that as a field in my User object which maps to the user table
@Entity
@Table(name = "USER")
public class User
{
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "fullName")
private String fullName;
//other fields ommited
@OneToOne
@JoinColumn(name = "id")
private Member member;
My member pojo looks as follows
@Entity
@Table(name = "MEMBER")
public class Member
{
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "sgpid")
private int sgpid;
@Column(name = "username")
private String username;
Trying to save the object i do as follows;
@Override
public boolean addUser(User user)
{
if (user == null)
{
throw new IllegalArgumentException("Unable to add null user");
}
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
return true;
}
This gives me the row saved in my user table but the entry is not inserted in to the member table. I think my linking annotations are probably incorrect but I am not too sure - please could someone provide some assistance.
Thanks
Upvotes: 0
Views: 1115
Reputation: 6574
First thing in your user class you should change the joinColumn to member_id.
As mentioned in another answer to persist a related entity you need to set the cascade to persist, i would recommend using cascade All which will involve the related entity in all operations check the doc https://docs.oracle.com/cd/E19798-01/821-1841/bnbqm/index.html
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "member_id")
private Member member;
Upvotes: 1
Reputation: 1615
Try to set the cascade value of the @OneToOne annotation:
@OneToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "id")
private Member member;
Upvotes: 1