Hibernate @Where annotation for ManyToOne relationship

I recently started refactoring my project because I had to add an extra column to some kind of my table. An additional column is Enum (Pending or Asset). Because of this change, I will now need to refactor ALL my queries to only get a row if the status is ACTIVE.

After some research, I found that we can annotate Entity with @Where annotation. it works great when i use it on a simple column, but the table looks like this:

@Where(clause = 'state='ACTIVE'")
@Entity
public class Place {

  @Column(name="id_place")
  private String placeId;

  @Column(name="name")
  private String palceName;

@OneToMany(mappedBy = "place")
    private Set<PlaceTag> placeTag;

  ...
  ...
}

@Where(clause = 'state='ACTIVE'")
@Entity
public class Tag {

  @Column(name="id_tag")
  private String tagId;

  @Column(name="name")
  private String tagName;

   @OneToMany(mappedBy = "tag")
    private Set<PlaceTag> placeTag;
   ... 
   ...
}

@Where(clause = 'poi.state='ACTIVE' AND tag.state='ACTIVE")
@Entity
public class PlaceTag {

  @Column(name="id")
  private String id;

  @ManyToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
  @JoinColumn(name = "place_id")
  private Place place;

  @ManyToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
  @JoinColumn(name = "tag_id")
  private Tag tag;

  ...
  ...

}

      

Now my question is, how do I make this statement ONLY return places and tags that are ACTIVE?

SELECT pt FROM PlaceTag pt;

      

Is it possible? Or should I write a request Explicitly?

thank

+4


source to share


1 answer


As you already discovered, or just using cases, the suggestion is @Where

just fine, but in your case you want to filter PlaceTag

by place and tag as well, so a join is required in this situation.

So you can save the clause @Where

for Place

and Tag

, whereas for PlaceTags

you need to use a JPQL query:



select pt
from PlaceTag pt
join pt.tag t
join pt.place p
where 
    t.state='ACTIVE' and p.state='ACTIVE'

      

At least until @WhereJoinTable

annotated to work for all-to-one associations too.

0


source







All Articles