I am very new to hibernate and I am working with JPA and Hibernate4. Trying to insert parent object in child as onetoone
relationship.
I went through some tutorials but All the example in the web shows, inserting both parent and child tables.
I want to insert data in child table only.
I have two tables called user and department.
User table consists of user details with department as onetoone relationship, as follows,
@Entity
@Table(name = "User")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "_id")
private String id;
@Column(name = "firstName")
private String firstName;
@Column(name = "lastName")
private String lastName;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "departmentId")
private Department departmentId;
// getters and setters...
}
Below is my Department entity,
@Entity
@Table(name = "Department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "_id")
private String id;
@Column(name = "name")
private String name;
// getters and setters...
}
In department table there is only 4 data. I want to insert data only in user data while insert into it and don't want to insert in Department.
How can I do that.Please assist.
You have to use mappedBy
for this, as mentoned below in child Table, Department
in your case
@OneToOne(mappedBy="department")
private UserEntity user;
These posts explain you better this,