简体   繁体   中英

How to query with hibernate and optional parameters?

Is it possible to write a select query with optional parameters?

Example: basically I want to fetch using the following query:

SELECT p from Person p where p.firstname = :firstname and p.lastname = :lastname;

But if this does not return a result, I want to query only by lastname.

Is that possible in a single query? Or should I execute an additional query within an open transaction?

As stated in the question linked by @MWiesner, there is no way as far as I'm aware to do this in hibernate HQL. However, if you're prepared to use hibernate to do a native query, you could use a case statement to achieve your aim. For example, the following query will work in MySQL, and with a small amount of tweaking could be made to work in any SQL database.

SELECT *
FROM Person p
WHERE (
  CASE (
    SELECT COUNT(*)
    FROM Person p2
    WHERE p2.firstname = :firstname AND p2.lastname = :lastname
     ) 
  WHEN 0 THEN 
    p.lastname = :lastname 
  ELSE 
    p.firstname = :firstname AND p.lastname = :lastname 
  END
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM