开发者

Searching in database

I need some advice how can I perform a search in the database. For example I have table in database called: Student the columns are: NAME, SURNAME, UNIVERSITY开发者_Go百科, AGE, COURSE.

When I'm filling the search form I do not specify SURNAME and UNIVERSITY and I want my search results to be every student where NAME = my specified name, AGE - my specified age and COURSE - my specified course and SURNAME and UNIVERSITY can be any.

Can someone give me some advice?

EDIT

Thanks for quick replay. But it seems I do not understand something or it is not working. Here is my real query:

SELECT UNIVERSITY, INFORMANT_NAME, AGE 
FROM informant 
WHERE UNIVERSITY='%VDU%' 
  AND INFORMANT_NAME='%Mindaugas Jonaitis%' 
  AND AGE='%21%';

It does not return me any result.

SELECT UNIVERSITY, INFORMANT_NAME, AGE 
FROM informant 
WHERE UNIVERSITY='VDU' 
  AND INFORMANT_NAME='Mindaugas Jonaitis' 
  AND AGE='21';

This query does, but only for specified values. I want that returned result will be all data from table where UNIVERSITY = 'VDU' or other values not provided or provided null or something that would be skipped.

SELECT UNIVERSITY, INFORMANT_NAME, AGE 
FROM informant 
WHERE UNIVERSITY='VDU' 
  AND INFORMANT_NAME='????'   
  AND AGE='????';


If you want to use wildcards you need to use LIKE, not =.

SELECT UNIVERSITY, INFORMANT_NAME, AGE 
FROM informant 
WHERE UNIVERSITY LIKE '%VDU%' 
  AND INFORMANT_NAME LIKE '%Mindaugas Jonaitis%' 
  AND AGE LIKE '%21%';

However using like with leading wildcards will disable any chance of using an index on that field.
If you are using MySQL with MyISAM, put an a fulltext index on the fields you want to search with wildcards and use:

SELECT UNIVERSITY, INFORMANT_NAME, AGE 
FROM informant 
WHERE UNIVERSITY LIKE '%VDU%' 
  AND MATCH(INFORMANT_NAME) AGAINST('Mindaugas Jonaitis')
  AND AGE LIKE '21%';

Match .. against will only work for search phrases longer than 4 chars. Also it really makes no sense to search with leading wildcards in age. I usually don't want to get all people who are 21,31,41, I often want to get all 20-somethings though.


There is many ways of doing so. But for all of them you need to grab a Session from Hibernate . From that point on you can:

  • Create a query object from a named query
  • Create a Query object from a sql string
  • Create a Criteria object

All of them then, just with either a query.list() or criteria.list().

For more info:

  • http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html
  • http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html


A findByExample DAO method is always useful here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜