English 中文(简体)
How can I do this simple search?
原标题:

I have a web app build with Hibernate. In one page, I have one submit button with 5 inputs

  • field1
  • field2
  • field3
  • field4
  • field5

When all the inputs are null, I make a simple query

Query query = session.createQuery("from MyTable");

but when I have at least one input not null, I must create the search query. Let s say, the field1 is not null:

Query query = session.createQuery("from MyTable where field1= :field1");
query.setParameter("field1", field1);

But I need to check every single input and I need to create the query String based on this thing.

What is the smartest, easiest way to create the search query?

问题回答

You could use a Criteria-Query instead:

Criteria criteria = hibernateSession.createCriteria(YourClass.class);

And then add a Criteria to your query based on every field:

if(fieldValue1 != null) {
    criteria.add(Restrictions.eq("FieldProperty1", fieldValue1))
}

if(fieldValue2 != null) {
    criteria.add(Restrictions.eq("FieldProperty2", fieldValue2))
}

...

Of course, that will only work if you use the native hibernate API instead of the JPA-API.





相关问题
How to do SQL IN like query in hibernate search

A simulating scenario is: Search for books whose content contains "success" AND author is in a list of passed names(could be thousands of). I looked into filter: http://docs.jboss.org/hibernate/...

Memory leak with paged JPA queries under JBoss AS 5.1

I m trying to integrate Hibernate Search into one of the projects I m currently working on. The first step in such an endeavour is fairly simply - index all the existing entities with Hibernate Search(...

Custom Lucene Sharding with Hibernate Search [closed]

Has anyone experience with custom Lucene sharding / paritioning using Hibernate Search? The documentation of Hibernate Search says the following about Lucene Sharding : In some cases, it is ...

How can I do this simple search?

I have a web app build with Hibernate. In one page, I have one submit button with 5 inputs field1 field2 field3 field4 field5 When all the inputs are null, I make a simple query Query query = ...

Hibernate-Search: How to search dates?

@Entity @Table(name = "USERS") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(name = "USERNAME", nullable = false, length = 20) private String ...

Hibernate Search Paging + FullTextSearch + Criteria

I am trying to do a search with some criteria FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(finalQuery, KnowledgeBaseSolution.class).setCriteriaQuery(criteria); and then page it ...

Hibernate Search with index in a different database

I have a database which is readonly (I only have the access to view), but I have to index this database for search. The DAO layer to this table is now using a generic DAO approach with Hibernate+JPA. ...

热门标签