0

hibernate query

asked 2010-03-24 17:32:20 +0800

yuanbohan gravatar image yuanbohan
258 2 7

I want to get one row data from the database using the session query, but anyone can help me with this how to get one object from the database with the hibernate query? Get a list of data is like this:

import org.zkoss.zkplus.hibernate.*;

import java.util.Date;
import java.util.List;

public class EventDAO {
org.hibernate.Session _session;

public EventDAO() {
_session = HibernateUtil.getSessionFactory().getCurrentSession();
}

public void saveOrUpdate(Event anEvent, String title, Date date) {
anEvent.setTitle(title);
anEvent.setDate(date);

_session.saveOrUpdate(anEvent);
}

public void delete(Event anEvent) {
_session.delete(anEvent);
}

public Event findById(Long id) {
return (Event) _session.load(Event.class, id);
}

public List findAll() {
return _session.createQuery("from Event").list();
}
}


I just want to get one Event object with a sql sentense just like: from events where time > '2010-03-23 00:00:01' order by time asc limit 1;
Can any one help me ? Thanks a lot. ^_^

delete flag offensive retag edit

1 Reply

Sort by ยป oldest newest

answered 2010-03-24 20:02:27 +0800

caclark gravatar image caclark
1753 2 5
http://clarktrips.intltwi...

You should add a findFirstByDate(Date theDate) to your DAO and call it passing it your required date.

public Event findFirstByDate(Date theDate)
{
    Event result = null ;

    Query query =_session.createQuery("from Event where time > ? order by time asc limit 1" )  ;
    query.setDate( 1, theDate ) ;
    List results = query.list() ; 
    if ( results != null 
      && results.size() > 0 )
        result = results.get(0) ;

    return result ;
}

Completely untested code; YMMV.

link publish delete flag offensive edit
Your reply
Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!

[hide preview]

Question tools

Follow

RSS

Stats

Asked: 2010-03-24 17:32:20 +0800

Seen: 240 times

Last updated: Mar 24 '10

Support Options
  • Email Support
  • Training
  • Consulting
  • Outsourcing
Learn More