本文共 2570 字,大约阅读时间需要 8 分钟。
hql 是hibernate查询语言 hibernate query language 是一种接近sql的查询语言。
hql查询 不会出现表名字,表的字段名,只会是类名和类的属性名。
1.新建java文件,生成唯一的SessionFactory:
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(); }
2.Hibernate3之后推荐用getCurruntSession来打开session,来保证线程安全。
(使用getCurrentSession需要在hibernate.cfg.xml配置文件中加入
<property name="hibernate.current_session_context_class"> thread </property>,保证每个读写线程有唯一的session实例 。)
org.hibernate.dialect.MySQLInnoDBDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/firstorm?useSSL=false root root true thread
事务:
try { sf = HibernateUtil.getSessionFactory(); session = sf.getCurrentSession(); ts = session.beginTransaction(); session.save(u); //ts.commit(); }
Query的查询 :
1.保存用户对象:
//保存 public void testSaveUser() { Configuration cfg = null; SessionFactory sf = null; Session session = null; Transaction ts = null; User u = new User(); u.setName("于佳欣"); u.setGender("女"); u.setAge(21); u.setBirthday(Date.valueOf("2000-01-01")); try { sf = HibernateUtil.getSessionFactory(); session = sf.getCurrentSession(); ts = session.beginTransaction(); session.save(u); ts.commit(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); if(ts != null) { ts.rollback(); } }finally { session.close(); sf.close(); } }
2.查询用户对象:
//查询 public void testQueryUser() { Configuration cfg = null; 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"); Listusers = query.List(); for(int i = 0; i < users.size(); i++) { User u = users.get(i); System.out.printIn(u.getName() + " " + u.getAge()); } ts.commit(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); if(ts != null) { ts.rollback(); } }finally { session.close(); sf.close(); } }
结果:
转载地址:http://dauhj.baihongyu.com/