0

I have an entity with a flag, like:

@Entity 
Class User{

  @Column
  private String name;

  @Column
  private Boolean excluded;

  // Getters, setters

}

I need to keep the excluded users on DB, but I really never retrieve it.

Is there a way to tell hibernate "do not get if excluded=1" without having to specify it in every single query I do with this entity?

(I simplified the problem to ask here, but the query I need to do is a lot bigger because of this flag restriction. If I could annotate the column to be mandatory =true when retrieving from DB, would be great)

The Student
  • 27,520
  • 68
  • 161
  • 264

1 Answers1

0

You can try to use hibernate @Filter in the following way:

  1. Filter definition:
@Entity
@FilterDef(
    name="excludedUser",
    parameters = @ParamDef(
        name="excluded",
        type="boolean"
    )
)
@Filter(
    name="excludedUser",
    condition="excluded_column = :excluded"
)
class User{

  @Column(name = "excluded_column")
  private Boolean excluded;

  // Getters, setters

}
  1. Filter usage:
entityManager
    .unwrap( Session.class )
    .enableFilter( "excludedUser" )
    .setParameter( "excluded", true);

List<User> users = entityManager.createQuery(
    "select u from User u", User.class)
.getResultList();

Limitations:

  1. Filters apply to entity queries, but not to direct fetching. So, the filter will not be applied to the following case:
User user = entityManager.find( User.class, 2L );
  1. This is not documented, but it looks like a filter does not apply for join entity.
SternK
  • 11,649
  • 22
  • 32
  • 46