2

I get the following exception:

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

the bean I use is:

@Entity
@Table(name="user")
public class User implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = -5689970869179555442L;

@Id
@Column(name="username")
/*@NotNull*/
private String username;

@Column(name="password")
private String password;

@Column(name="email")
/*@Email*/
private String email;

@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany
@JoinTable(name="user_follower",joinColumns={@JoinColumn(name="username")},
        inverseJoinColumns={@JoinColumn(name="follower")})
private List<User> followers = new ArrayList<User>(0);

/*@LazyCollection(LazyCollectionOption.FALSE)*/
@OneToMany(fetch=FetchType.EAGER)
@JoinTable(name="user_message",joinColumns={@JoinColumn(name="username")},
        inverseJoinColumns={@JoinColumn(name="message_date")})
@OrderBy(value="messageDate")
private List<Message> messages = new ArrayList<Message>(0);

public User() {

}

in the dao I have the following code:

public void followUser(String userToFollow, String username) {
    System.out.println("repository invoked");
    session=sessionFactory.getCurrentSession();
    User user=retrieveUser(username);
    @SuppressWarnings("unchecked")
    List<User> followers=session.createCriteria(User.class).setFetchMode("followers", FetchMode.JOIN)
    .add(Restrictions.eq("username", username)).list();
    for(User follower: followers){
        if(follower.getUsername().equals(userToFollow)){
            //do nothing
        }else{
            followers.add(retrieveUser(userToFollow));
            user.setUserFollowers(followers);
        }
    }
    session.saveOrUpdate(user);
}

I don't know what to do to prevent such exception

Muhammad Bekette
  • 1,396
  • 1
  • 24
  • 60

1 Answers1

7

I had similar problem, and I resolved it by changing the List to Set. I think then Hibernate doesn't need to care about ORDER BY (just guessing).

amorfis
  • 15,390
  • 15
  • 77
  • 125
  • 3
    Alternatively, you can do @LazyCollection(LazyCollectionOption.FALSE) I like your approach better though as the annotations are consistent and the data type being used more acurately represents our data – Christian Bongiorno Sep 27 '12 at 20:20