0

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.

Community
  • 1
  • 1
Bharat
  • 407
  • 2
  • 7
  • 16
  • 1
    can you share your User class? – mendieta Oct 15 '14 at 20:12
  • Please check if(user.getUserId()==userDetails.getUserId()) is returning true (in case both the User class is same in your code). If yes, then this is where the problem exists. – Amitesh Rai Oct 15 '14 at 20:49
  • Also , you should share the required info while asking questions. No one is going to hit the fish eye without any hint of what and where. – Amitesh Rai Oct 15 '14 at 20:52

1 Answers1

0

In your case you are assigning @ManyToOne Mapping and passing only single object.

So change Model mapping with

@ManyToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinColumn(name="USER_ID")
List<User> users;

    public List<User> getUsers() {
        return users;
    }
    public void setUsers(List<User> users) {
        this.users = users;
    }

Now when you are saving company entity then pass List of users to setUsers method

Harshal Patil
  • 6,659
  • 8
  • 41
  • 57