简体   繁体   中英

How do I solve this Hibernate JPA query?

I'm trying to build a query with criteriabuilder.

The object structure is like this User -> has a list called "userRoles"...userRoles contains objects of class UserRoleEntity.

each UserRoleEntity has one RoleEntity.

each RoleEntity has a "name" that I want to filter.

So my query for now:

ListJoin<UserEntity, UserRoleEntity> userRoles = user.joinList("userRoles", JoinType.INNER);

predicates.add(userRoles.get("role").<RoleEntity> get("name").in("abc"));

But it's not working... any suggestions?

Thanks.

Based on the code fragment, it is difficult to identify an exact cause of the error.

However, assuming these entities

@Entity
@Table(name="t_user")
public class UserEntity {

    @Id
    @Column(name="id")
    private Integer id;
    @Column(name="name")
    private String name;
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    List<UserRoleEntity> userRoles;

    //...
}


@Entity
@Table(name="t_user_role")
public class UserRoleEntity {
    @Id
    @Column(name="id")
    private Integer id;
    @ManyToOne
    private UserEntity user;
    @OneToOne
    @JoinColumn(name = "role_id")
    private RoleEntity role;

    //...
}

@Entity
@Table(name="t_role")
public class RoleEntity {
    @Id
    @Column(name="id")
    private Integer id;
    @Column(name="name")
    private String name;

    //...
}

the following method on a custom repository

List<UserEntity> findUserByRoleName(String roleName) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<UserEntity> cq = cb.createQuery(UserEntity.class);

    Root<UserEntity> root = cq.from(UserEntity.class);
    Join<Object, Object> joinUserRole = root.join("userRoles");
    Join<Object, Object> joinRole = joinUserRole.join("role");

    Predicate predicateRoleName = cb.equal(joinRole.get("name"), roleName);
    cq.where(predicateRoleName);

    TypedQuery<UserEntity> query = entityManager.createQuery(cq);
    return query.getResultList();
}

generates the desired query:

select userentity0_.id as id1_2_, userentity0_.name as name2_2_
    from t_user userentity0_
    inner join t_user_role userroles1_ on userentity0_.id=userroles1_.user_id
    inner join t_role roleentity2_ on userroles1_.role_id=roleentity2_.id
    where roleentity2_.name=?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM