Hibernate 查询在一对多中无法正确投影
我正在执行一个查询,需要返回用户,该查询也填充了 UserConnectors。我的查询不断返回两个结果,而不是单个 ID 的一个结果。它应该是一个结果,但我认为 UserConnector 连接因为用户有两个,所以在结果中创建两个用户,每个用户连接器一个。
表
用户: ID NAME UserConnector:ID、USERID、DATE
User.java
@OneToMany(mappedBy="user")
public Set<UserConnector> getUserConnectors() {
return this.userConnectors;
}
/**
* Set the list of Connectors
*/
public void setUserConnectors(Set<UserConnector> userConnectors) {
this.userConnectors = userConnectors;
}
UserConnector.java
@ManyToOne
@JoinColumn(name = "USERID")
public User getUser() {
return this.user;
}
/**
* set users
*/
public void setUser(User user) {
this.user = user;
}
查询
Criteria criteria = userRepository.getCritieria();
criteria.createAlias("userConnectors", "uc", Criteria.LEFT_JOIN);
criteria.add(Restrictions.eq("id", request.getId()));
criteria.add(Restrictions.eq("enabled", new Long("1")));
criteria.add(Restrictions.eq("uc.active", new Long("1")));
List<User> list = userRepository.findByCriteria(criteria);
I am doing a query where I need to get a user back, that also has UserConnectors populated with it. My Query keeps bringing back two results instead of one for a single ID. It should be one result, but I think the UserConnector join since the User has two of them, is creating two Users in the result, one for each User Connector.
Tables
User: ID NAME
UserConnector: ID, USERID, DATE
User.java
@OneToMany(mappedBy="user")
public Set<UserConnector> getUserConnectors() {
return this.userConnectors;
}
/**
* Set the list of Connectors
*/
public void setUserConnectors(Set<UserConnector> userConnectors) {
this.userConnectors = userConnectors;
}
UserConnector.java
@ManyToOne
@JoinColumn(name = "USERID")
public User getUser() {
return this.user;
}
/**
* set users
*/
public void setUser(User user) {
this.user = user;
}
Query
Criteria criteria = userRepository.getCritieria();
criteria.createAlias("userConnectors", "uc", Criteria.LEFT_JOIN);
criteria.add(Restrictions.eq("id", request.getId()));
criteria.add(Restrictions.eq("enabled", new Long("1")));
criteria.add(Restrictions.eq("uc.active", new Long("1")));
List<User> list = userRepository.findByCriteria(criteria);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你能试试这个吗?
Can you try this?
与 HQL 一样,对于带有连接的
Criteria
,您需要手动触发不同的投影:As well as with HQL, for
Criteria
with joins you need to trigger distinct projection manually: