Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

java - Optional parameters with named query in Hibernate?

Is there any way to specify optional parameters (such as when search parameters are provided from a form and not all parameters are required) in a named query when using Hibernate? I'm using a native SQL query, but the question is probably applicable to named HQL queries as well.

I'm pretty sure the answer to this is 'no', but I haven't found the definitive answer in the documentation yet.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As mentioned in a different answer to the question referenced previously, the following HQL construct works for me:

select o from Product o WHERE :value is null or o.category = :value

if :value is passed in as null, all Products are returned.

See also Optional or Null Parameters

Note that this won't work in some versions of Sybase due to this bug, so the following is an alternative:

select o from Product o WHERE isnull(:value, 1) = 1 or o.category = :value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...