Precedence in JPA Query

1

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

    
asked by anonymous 27.11.2018 / 14:27

1 answer

0
  

the query will override or will use my where clause in the entity also in the repository

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

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

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

The @Filter works a> similar to @Where , but you determine when to use it. The problem is that it needs to be enabled in the Hibernate session, which may be something 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 {

Native SQL , it can be invoked using @Query with 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 to map a new field , you can create a new mapping for the column which is involved in the @Where clause but using another name. In your query, you start using this new column and not the column that is in @Where :

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

@Column(name = "ts_removed", insertable=false, updateable=false)
private Date tsRemovidoSemWhere;
    
17.12.2018 / 19:02