2

I have User entity:

public class User implements IStandarizedEntity {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Long id;

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "web.user_role",
        joinColumns = {
            @JoinColumn(name = "user_id", referencedColumnName = "id")},
        inverseJoinColumns = {
            @JoinColumn(name = "role_id", referencedColumnName = "id")})
@Size(min = 1, max = 10)
private List<Role> roles = new ArrayList<>();

A a Role entity:

public class Role implements IStandarizedEntity {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Long id;

@Column(name = "type")
@Enumerated(EnumType.STRING)
private ERole type;

I am using hibernate like a jpa provider. I want to only get users with specific role. I wrote named query to retrieve all users and now I am trying to use @Filter to retrieve only users with specified role type.
What I achieved is that I can retrieve all users and next while loading roles I can load filtered roles list but it is not what I want to do.

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

1

You can just filter the role when querying. For example:

Select u from User u join fetch u.roles r where r.type = :roleType;

Join fetch will return all users with roles matching your filter.

thanh ngo
  • 834
  • 5
  • 9
  • Hi, thanks for response, but I have to sometimes do filtering and sometimes not. It depends what request I got from frontend. I think to do this by session.enableFilter() when filtering is required, and using @Filter to specify filtering. – Sebastian Szwaczyk Aug 05 '16 at 15:00
  • You can take a look at [here](http://stackoverflow.com/questions/6919686/annotation-to-filter-results-of-a-onetomany-association) to find out how to implement. For me, i will just create a dynamic query using CriteriaQuery. – thanh ngo Aug 05 '16 at 15:08