Select a single item from a database using Spring Hibernate Sessionfactory

This is in my DAO:

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

This gets all the elements from the Weather table. But let me say that I want to do something like this (I want only one element from the Weather table):

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

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

+8
java spring hibernate sessionfactory
source share
3 answers

If you have an identifier, you simply use get:

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

If you need to make a request, you will have to grab the top of the result set, or you can use uniqueResult() in the request.

+11
source share

Is there something wrong with getting the list? :) Even if you know that only 1 sleep mode cannot accept it. Listing is safer anyway!

 public Weather getCurrentWeather() { List<Weather> list = sessionFactory.getCurrentSession().createQuery("from Weather where id = 1").list(); // here should be something else than list() return (list.isEmpty() ? null : list.get(0)); } 
+7
source share

You need to use the criteria API, as shown below:

  List<LeaveManagement> leaveManagements = session.createCriteria(LeaveManagement.class) .add( Restrictions.isNull("approvedTimeStamp") ) .list(); If you want to write a hql query you can write as: String hql = "from LeaveManagement where approvedTimeStamp is null"; Query query = session.createQuery(hql); List results = query.list(); 
0
source share

All Articles