1

I have a one to many relationship between two of my entites, Airport and AirportTranslation:

public class Airport {
    @Id
    @Column(name = "id")
    private Long id;

    @OneToMany(mappedBy="airport", fetch = FetchType.LAZY)
    private List<AirportTranslation> translations;
}

And:

public class AirportTranslation implements Serializable {
    @Id
    @Column(name = "id", updatable = false)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "airport_id")
    private Airport airport;

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

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

Now I want to get all translations of an airport based on the current language of the system, using the normal syntax: airport.getTranslations().

Due to the fact that the current language is dynamic, I can not use hibernate @Where.

I think using Hibernate @Filter could be the best option, but I can't find any clean, working sample of that for spring boot applications.

Hamid Mohayeji
  • 3,977
  • 3
  • 43
  • 55

1 Answers1

3

There are few options.

Java Filtering

Easy one, but slow and something I would consider design smell,to filter all data in getter.

We'd much rather prefer to filter data in database for performance reasons.

Query Filtering

Other option is to manually add filters to your repositories, yet you would have to ALWAYS remember to put filters in your queries, every time you add new one.

Which creates some maintenance issues.

Hibernate Filtering

To get Hibernate Filtering and Spring Data Jpa is a little bit tricky.

Since Spring Repositories are the abstraction to not interact with EntityManagers/ Session objects, yet we have to set filtering on our session for query we want to make, which is pretty much the same as making manual filters.

For more information on this solution, please refer to LINK

Spring Specifications

The cleanest and most fitting for filtering with some business/system logic, I'd consider using Spring Specifications. There is a chapter in Spring documentation about that with some great examples, so I won't be copy-pasting that.

Please refer to https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#specifications

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Emil Hotkowski
  • 2,233
  • 1
  • 13
  • 19
  • 2
    Nice answer! I came across a very good tutorial on Specifications here https://leaks.wanari.com/2018/01/23/awesome-spring-specification/ – Khwaja Sanjari Oct 18 '18 at 15:11