开发者

Hibernate Query Not Projecting Correctly in One To Many

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开发者_如何学JAVA 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);


Can you try this?

  List users = session.createCriteria(User.class)
  .add( Restrictions.idEq(request.getId()))
  .add( Restrictions.eq("enabled", new Long("1")))
  .createCriteria("userConnectors")
      .add( Restrictions.like("active", new Long("1")) )
  .list();


As well as with HQL, for Criteria with joins you need to trigger distinct projection manually:

 criteria.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);


criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜