[英]Hibernate manyToMany only returns one element
I want to read several Elements for a user using Hibernate. 我想为使用Hibernate的用户阅读几个Elements。
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.
所以我的元素类中没有'users'-field。
If I try to read a user, I only get the first element of the mapping. 如果我尝试读取用户,我只会获得映射的第一个元素。 Insert and update works fine.
插入和更新工作正常。
Any ideas?? 有任何想法吗?? Thanks!
谢谢!
Oh hell I´m so stupid! 哦,天哪,我太蠢了! In the dao which I use to load my entities, i had the following restriction:
在我用来加载我的实体的dao中,我有以下限制:
criteria.setMaxResults(1);
I wanted to load only one entity out of the database. 我想只从数据库中加载一个实体。 I didn´t know how hibernate works.
我不知道hibernate是如何工作的。 Now, I figured out, that this restriction causes hibernate to get only one Row of the joined tables.
现在,我想通了,这个限制导致hibernate只获得连接表的一行。 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.
现在,dao的查询返回多个相同对象的列表。 And I only have to choose the first one.
我只需要选择第一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.