Hibernate Query查询
单例模式
package Dao;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Configuration cfg = null;
private static SessionFactory sf = null;
static {
try {
cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//
public static SessionFactory getSessionFactory() {
return sf;
}
//
public static void closeSessionFactory() {
sf.close();
}
}
}
}
查询
public void testQueryUser() {
SessionFactory sf=null;
Session session =null;
Transaction ts=null;
try {
sf=HibernateUtil.getSessionFactory();
session =sf.getCurrentSession();
ts=session.beginTransaction();
Query query=session.createQuery("from User");
List<User> users =query.list();
for(User u:users) {
System.out.println(u.getName()+" "+u.getGender()+" "+u.getAge()+" "+u.getBirthday());
}
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if(ts!=null) {
ts.rollback();
}
}
}
结果