【问题标题】:crazy hibernate criteria with extra condition on join?加入额外条件的疯狂休眠标准?
【发布时间】:2014-03-01 09:19:28
【问题描述】:

我有 2 个相关的实体:

@Entity
public class Base_Group implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    private String id;
    @Column(unique = true, nullable = false)
    private String name;
    @ManyToMany(mappedBy = "groups", fetch = FetchType.LAZY )
    private Set<Base_Role> roles = new HashSet<Base_Role>(0); 
    ...

@Entity
public class Base_Role implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    private String id;
    @Column(nullable = false)
    private String name;
    @ManyToMany(fetch = FetchType.EAGER)
    private Set<Base_Group> groups = new HashSet<Base_Group>(0); 
    ...

我想使用这个条件获取数据:

Criteria criteria = hem.getSession().createCriteria(Base_Group, "g");
criteria.setProjection( Projections.projectionList()
                .add( Projections.property("g.id"), "id" )
                .add( Projections.property("g.name"), "name" )
                .add( Projections.property("roles.id"), "roleId" ) )
            .createAlias("g.roles", "roles", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("roles.id", roleId))
            .setResultTransformer(Transformers.aliasToBean(RoleGroups.class));

但是标准做出了这样的错误查询:

select this_.id as y0_, this_.name as y1_, roles1_.id as y4_ from Base_Group this_ 
left outer join Base_Role_Base_Group roles3_ on this_.id=roles3_.groups_id and ( roles1_.id=? ) 
left outer join Base_Role roles1_ on roles3_.roles_id=roles1_.id and ( roles1_.id=? ) 

虽然在第一次加入时有糟糕的额外条件。有什么想法可以解决这个标准吗?

【问题讨论】:

    标签: java hibernate criteria


    【解决方案1】:

    因为你在这里做了:

    .createAlias("g.roles", "roles", JoinType.LEFT_OUTER_JOIN, Restrictions.eq("roles.id", roleId))
    

    用途:

    ...
    .createAlias("g.roles", "roles", JoinType.LEFT_OUTER_JOIN)
    .setResultTransformer(Transformers.aliasToBean(RoleGroups.class))
    .add(Restrictions.eq("roles.id", roleId));
    

    但是,我建议使用 HQL。那是一个具有单一限制的静态查询。

    【讨论】:

    • 如果我按照你说的做,我会丢失哪些角色.id 与 roleId 不相等的记录,而我希望它们使用 null 作为 roleId(左连接而不是内连接),此外在这种情况下,我的标准是动态的,但我简要介绍了它的条件。
    • 它是真的......我认为这是一个 Hibernate 错误。
    猜你喜欢
    • 2016-01-27
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多