Question

I have 2 entities that are related :

@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); 
    ...

and I want to fetch data using this criteria:

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));

but criteria made bad query like this :

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=? ) 

while had bad extra condition in first join. any idea to solve this criteria?

No correct solution

OTHER TIPS

Because you did it here:

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

Use:

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

But, I recomend do it with HQL. Thats a static query with a single restriction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top