Fixus
Fixus

Reputation: 4641

Hibernate doesn't add records to association

I have a m:n relation beetwen objects (Meeting, Person) as many persons can be participant of many meetings.

I've set it like this

Meeting

    @ManyToMany(mappedBy = "meetings")
protected Set<Person> participants = new HashSet<Person>();

Person

@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name = "person_meeting",
        joinColumns = {@JoinColumn(name = "person_id")},
        inverseJoinColumns = {@JoinColumn(name = "meeting_id")}
)
protected Set<Meeting> meetings = new HashSet<Meeting>();

Id DB hibernate created me table meeting_participants with two fields: meeting_id, person_id. Cool, just as I wanted. Now problematic case. I've create Meeting object and I saved it to DB. Than I create set of users, I add it to meeting

this.saveMeeting.setParticipants(set);

Hibernate displays:

Hibernate: update Meeting set duration=?, meetingDate=?, room=? where meeting_id=?

Nothing added to association. What do I need to change ?

// EDIT I've changed in Meeting definition of the field

@ManyToMany(mappedBy = "meetings", cascade = {CascadeType.ALL})
protected Set<Person> participants = new HashSet<Person>();

Now I get error

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions

It is in this method

public static Long add(Meeting meeting) {
    SessionFactory sf = null;
    Session session = null;

    sf = HibernateUtil.getSessionFactory();
    session = sf.openSession();

    session.beginTransaction();
    try{
        session.save(meeting);
        session.getTransaction().commit();
        session.flush();
    } catch(HibernateException e){
        session.getTransaction().rollback();
        e.printStackTrace();
        return new Long(-1);
    }
    session.close();

    return meeting.getId();
}

The line that is causing the problem is:

session.save(meeting);

EDIT

Ok I've closed session properly. Everything works find BUT only when I'm creating new objects. When I want to update association it doesn not work. So the question is. How to update association ??

Upvotes: 0

Views: 193

Answers (2)

Fixus
Fixus

Reputation: 4641

I've solved the problem. I didn't think about that so I didn not wrote it. Person was a top class and it was extended by two others. I've changed update action so that it took an instance of Object class. That way I'm able to update association

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691765

This question is asked every two days. You just initialized one side of the association, and you chose the one that Hibernate ignores. A bidirectional association has an owner side, and an inverse side. Hibernate only considers the owner side. And the owner side is the one which doesn't have the mappedBy attribute.

So you need to initialize the other side of the association:

for (Participant p : set) {
    p.getMeetings().add(saveMeeting);
}

Upvotes: 2

Related Questions