问题
I want to read several Elements for a user using Hibernate.
These are my tables in the database:

@Entity
@Table(name="users")
public class User
{
@Id
@GeneratedValue
@Column(name="user_id")
private int id;
@ManyToMany(fetch=FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name="mapping",
joinColumns=@JoinColumn(name="user_id"),
inverseJoinColumns=@JoinColumn(name="element_id")
)
private Set<Element> elements;
It is an unidirectional mapping. So there is no 'users'-field in my elements-class.
If I try to read a user, I only get the first element of the mapping. Insert and update works fine.
Any ideas?? Thanks!
回答1:
Oh hell I´m so stupid! In the dao which I use to load my entities, i had the following restriction:
criteria.setMaxResults(1);
I wanted to load only one entity out of the database. I didn´t know how hibernate works. Now, I figured out, that this restriction causes hibernate to get only one Row of the joined tables. So I got only one element in the list of my entity.
Deleting this single line fixed my problem! Now, the query of the dao returns a list of multiple, identical objects. And I only have to choose the first one.
来源:https://stackoverflow.com/questions/24121020/hibernate-manytomany-only-returns-one-element