Hibernate 单例模式及query查询
HibernateUtil
public class HibernateUtil {
private static SessionFactory sf = null;
private static Configuration cfg = 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();
}
}
配置hibernate.cfg.xml
添加
<property name="hibernate.current_session_context_class">thread</property>
使用query查询
try {
sf = HibernateUtil.getSessionFactory();
session= sf.openSession();
ts = session.beginTransaction();
Query query = session.createQuery("from user");
List<user> User = query.list();
for (int i=0;i<User.size();i++){
user users= (user) User.get(i);
System.out.println(users.getName()+"的密码"+users.getPassword());
}
ts.commit();
} catch (HibernateException e) {
e.printStackTrace();
if(ts !=null){
ts.rollback();
}
}finally {
session.close();
sf.close();
}
结果