I'm trying to write a search, using Hibernate that would run search on different types of variables. I have a model Movie, that has properties: title, director, genre, year. Title, director, genre are strings, year is an int.
In the jsp file I have a select that will choose the property by which I want to search, and then a text input where I enter the property value. So it can be for example: Title: Some title, Year: 2000, etc.
I pass those values to the controller. Now, I have such methods in my hibernate classes:
public Movie findByProperty(String searchCriteria, String criteriaValue) {
Criteria criteria = getCurrentSession().createCriteria(Movie.class);
Movie movie = (Movie) criteria.add(Restrictions.eq(searchCriteria, criteriaValue)).uniqueResult();
return movie;
}
and
public Movie findByProperty(String searchCriteria, String criteriaValue) {
jdbcMovieDao.openCurrentSession();
Movie entity = jdbcMovieDao.findByProperty(searchCriteria, criteriaValue);
jdbcMovieDao.closeCurrentSession();
return entity;
}
And in the controller:
public String findMovieBy(ModelMap modelMap, @RequestParam(required = true) String searchCriteria,
@RequestParam(required = true) String criteriaValue) {
Movie movie = movieService.findByProperty(searchCriteria, criteriaValue);
It works fine when I select String properties, but I also want to be able to select year as criterium. I could probably put some if here, but I don't want to do it - not unless there is a nicer way. Can anyone tell me how to do it 'properly'. Please, be gentle, I'm a beginner. :-)