Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override @Where clause condition in Hibernate 4.3.4

I have a sample code piece like this-

@Entity
@Table(name = "employee")
@Where(clause = "active IS TRUE")
public class Employee{
}

This will fetch all the record of employee table having active=true or 1. In some cases, it may require that I want to load the records having active=false or 0.

If I write my code as FROM Employee emp WHERE emp.active IS FALSE but the generated query contains bot the conditions given in HQL and Annotations.

Hence, the expected results is not coming. Is there anyway to override this predefined @Where defined over entity?

like image 900
joy-cs Avatar asked Jul 03 '15 07:07

joy-cs


2 Answers

I know its too old question but I was facing same issue and thought I should share my workaround.

Totally agree with @cнŝdk answer as you cannot override but you can ignore @Where clause by defining nativeQuery as below:

@Query(value = "Select * from customer where company_id = ?1", nativeQuery = true) List<Customer> findByCompanyIdIgnoringEntityWhere(Long companyId);

The SQL in the @Query annotation must point the table's name and the fields' names (not entity's name).

like image 142
Malay Shah Avatar answered Oct 14 '22 08:10

Malay Shah


AFAIK you can't override it inside your class because if you take a look at the @Where documentation you will see that this interface is annotated @Retention(value=RUNTIME) so it has RUNTIME as a RetentionPolicy and you can see in the RetentionPolicy documentation that:

RUNTIME: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

Which force the @Where annotation to be recorded in the class file by the compiler and retained by the VM at run time, so it will be applied all over this class.

like image 34
cнŝdk Avatar answered Oct 14 '22 09:10

cнŝdk