Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 232
Jaanus Avatar asked Sep 16 '11 15:09

Jaanus


1 Answers

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.

like image 94
Affe Avatar answered Oct 10 '22 22:10

Affe