Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write JPA query with boolean condition

In my project i am using JPA 2.0 with eclipselink inplementation, an I have following problem:

I have defined entity with boolean column:

@Entity public User {      @Id     @GeneratedValue(strategy = GenerationType.IDENTITY)     @Column(name="USR_ID")     private Short id;      @Column(name="USR_NAME")     private String name;      @Column(name="USR_ACTIVE")     private boolean active;      .......  } 

I want to create query which will return all active users, something like this:

select u from User u where u.active = TRUE;

But if I use that query I got exception that boolean can't be cast to Short (column in database is stored as smallint). Is there any correct way how to write this query?

Thanks

like image 419
Rado Skrib Avatar asked Jun 06 '11 11:06

Rado Skrib


People also ask

Can we write SQL query in JPA?

@Danny I have updated the answer that will answer your question. The SQL query is in written in JPQL. You can also use native SQL query if you want with NativeQuery option. lr is an alias to LoanReport entity to be used in other parts of a JPQL query.

What is NativeQuery true in JPA?

We can use @Query annotation to specify a query within a repository. Following is an example. In this example, we are using native query, and set an attribute nativeQuery=true in Query annotation to mark the query as native. We've added custom methods in Repository in JPA Custom Query chapter.

How does JPA findById work?

Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.


1 Answers

Use the following form:

SELECT e FROM Employee e WHERE e.active = TRUE 

See the docs for more info.

like image 52
YUIOP QWERT Avatar answered Sep 23 '22 15:09

YUIOP QWERT