简体   繁体   中英

Spring Data JPA (Hibernate) One to Many Relationship with Dynamic Condition

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM