问题描述
这些是我在数据库中的表格:
<$
@Id
@GeneratedValue $
$ @Entity
@Table(name =users)
public class User
b $ b @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>要素;
这是一个单向映射。因此,在我的元素类中没有'用户'字段。
如果我尝试读取用户,我只会得到映射的第一个元素。插入和更新工作正常。
任何想法?感谢!
哦,地狱我真的很愚蠢!
在我用来加载我的实体的dao中,我有以下限制:
criteria.setMaxResults(1 );
我只想从数据库中加载一个实体。
我不知道hibernate是如何工作的。
现在,我想通了,这个限制导致hibernate只能得到连接表中的一行。所以我在我的实体列表中只有一个元素。
删除这条单行解决了我的问题!现在,dao的查询返回多个相同对象的列表。我只需要选择第一个。
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!
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.
这篇关于休眠manyToMany只返回一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!