I have created entity bean as Company which has @ManyToOne
relationship with User. how can we achieve using hibernate.
@Entity
@Table(name="company_details")
public class Company implements Serializable {
private Long id;
private String nameOfCompany;
private User createdBy;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="Id", nullable=false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name="NAME_OF_COMPANY", nullable=false)
public String getNameOfCompany() {
return nameOfCompany;
}
public void setNameOfCompany(String nameOfCompany) {
this.nameOfCompany = nameOfCompany;
}
@ManyToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinColumn(name="USER_ID")
public User getUsers() {
return users;
}
public void setUsers(User users) {
this.users = users;
}
}
while i am saving company object, hibernate throws below exception:
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.myProject.models.User#23]
Save code as below:
Company company = new Company();
company.setNameOfCompany("my comp");
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
com.myProject.models.User userDetails = userProfileService.getUserInfoByUserName(user.getUsername());
customer.setUsers(userDetails);
Long id = companyService.save(company);
DAO:
public Long save(Company comp) throws Exception {
sessionFactory.getCurrentSession().save(comp);
return comp.getId();
}
I already gone through Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session post but it seams not useful for me.