Precedence in Query JPA

Asked

Viewed 67 times

1

I’m using the notation @Where(clause = "ts_removed is null") in my entity. If I insert a method with @Query(value = "XXX") in my repository, the query will overwrite or use my Where clause inserted in the entity also in the repository?

1 answer

0

query will overwrite or use my Where clause inserted in the entity also in the repository

The clause of @Where inserted into the entity will also be used in the repository.

Therefore, I recommend avoiding the use of @Where. Once you have the case where you need to not use it, you will need to refactor the application to accommodate this change.

You have three alternatives: @Filter, SQL native or map a new field.

The @Filter works in a similar way to @Where, but you determine when to use. The problem is that it needs to be enabled in the Hibernate session, which can be quite verbose or laborious with Spring.

Example with Spring:

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
Session session = sessionFactory.openSession();
session.enableFilter("tsRemovido"); // se não habilitar, a condição será ignorada na consulta
Query query = session.createQuery("SELECT e FROM Entidade e");
//resto do código

Entity:

@Filters( {
    @Filter(name="tsRemovido", condition="ts_removed is null")
} )
public class Entidade {

Already with SQL native, he may be invoked using the @Query with the attribute nativeQuery = true:

@Query(value = "SELECT e FROM Entidade e", nativeQuery = true)

However, when using native SQL, you will not have the convenience of using the Hibernate entity to receive the information.

If you want map a new field, you can create a new mapping for the column that is involved in the clause @Where but using another name. In your query, you now use this new column and not the column that is in the @Where:

@Column(name = "ts_removed") // usado pelo @Where
private Date tsRemovido;

@Column(name = "ts_removed", insertable=false, updateable=false)
private Date tsRemovidoSemWhere;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.