I'm working in the Spring Framework. How do I pass object variable values into the Hibernate criteria restriction?
This is how I've written them:
@Repository
public class EventSearchDAOImpl implements EventSearchDAO<Event> {
@Autowired
private SessionFactory sessionFactory;
private Session session;
private Transaction trans;
@Override
public List<Event> getAll(Event event) {
session = sessionFactory.openSession();
System.out.println(event.getType()+event.getName());
return session.createCriteria(Event.class).add(Restrictions
.and(Restrictions.like("type", "%"+event.getType()+"%"),
Restrictions.like("name", "%"+event.getName()+"%")))
.list();
}
}
I printed the values in my output console to check via System.out.println(event.getType()+event.getName());
and they do seem to get passed successfully.
This is how I'm passing them via my DefaultController.java
class:
@RequestMapping(value = "/searchEvent", method = RequestMethod.POST)
public String searchEvent(Event event, Model model) {
Event e = new Event();
e.setType(event.getType());
e.setName(event.getName());
model.addAttribute("check", eventSearchDAO.getAll(e));
return "redirect:/";
}
A form in my index.jsp
page posts data into the above line of code.
To check if the code works, I added the following bit in my index.jsp
:
<c:forEach var="i" items="${check}">
${i.name} || ${i.type} <br>
</c:forEach>
If I manually write the restrictions as
return session.createCriteria(Event.class).add(Restrictions
.and(Restrictions.like("type", "%fair%"),
Restrictions.like("name", "%auto%")))
.list();
and make a few tweaks in the controller accordingly, it works just fine. But when I do it by passing the object's variables, it doesn't seem to work. That's my problem. Please help me fix this.
Turns out there was a mistake in my Controller class DefaultController.java
, I should've wrote:
return "index";
instead of:
return "redirect:/";
Yes, I'm an idiot.