Question

I have a complex query e.g. search employees with name, age, address, etc I would like to append a WHERE clause if a parameter IS NOT NULL.

for example (pseudo code):

if (age != null) // then append age to the where clause
    whereClause += whereClause + AND age = :age" 

I would like to use a NamedQuery in an XML file, but a NamedQuery does not support conditional where like myBatis

Can anyone help me resolve this problem?

Était-ce utile?

La solution

For this simple case/condition you can solve the problem with a NamedQuery:

SELECT e FROM Entity e WHERE (:age IS NULL) OR (:age IS NOT NULL and e.age=:age)

If you want more complex queries (e.g. where you sort dynamically by the column), I would use Criteria API.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top