Sebastian Szwaczyk
Sebastian Szwaczyk

Reputation: 91

How to get entities when oneToMany relation contains values using Hibernate Filters

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.

Upvotes: 2

Views: 540

Answers (1)

thanh ngo
thanh ngo

Reputation: 844

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.

Upvotes: 1

Related Questions