Hibernate manyToMany only returns one element

最后都变了- 提交于 2020-01-03 18:53:11

问题


I want to read several Elements for a user using Hibernate.

These are my tables in the database:

And this is the code of my user class:
@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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!