Jaanus Jaanus - 8 days ago 7
Java Question

Select single item from database with Spring Hibernate Sessionfactory

This is in my DAO:

public List<Weather> getCurrentWeather() {
return sessionFactory.getCurrentSession().createQuery("from Weather").list();
}


This gets all of the elements from table Weather. But lets say I wanna do something like this(I want only one element from table Weather):

public Weather getCurrentWeather() {
return sessionFactory.getCurrentSession().createQuery("from Weather where id = 1").list(); // here should be something else than list()
}


I know there should not be
list()
in the end, but what must I write there, to get only one object?

Answer

If you have an id, you just use get:

public Weather getCurrentWeather() {    
    return sessionFactory.getCurrentSession().get(Weather.class, 1); 
}

If you do need to do a query, yeah you'll have to grab the top of the result set, or you can use uniqueResult() on the query.