hibernate使用
Posted 奔跑在梦想的道路上
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate使用相关的知识,希望对你有一定的参考价值。
hibernate是一个ORM框架。
ORM的全拼是Object Relational Mapping,译为“对象关系映射”,是一种程序技术,用于实现面向对象编程语言里不同类型系统的数据之间的转换。从效果上来说,它其实是创建了一个可以在编程语言里使用的“虚拟对象数据库”。
使用较多的ORM框架有:
JPA---- Java Persistence API.JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系(只有接口规范) Hibernate---- 最流行ORM框架,通过对象-关系映射配置,可以完全脱离底层SQL MyBatis---- 本是apache的一个开源项目 iBatis,支持普通 SQL查询,存储过程和高级映射的优秀持久层框架 Apache---- DBUtils Spring---- JDBCTemplate
接下来,我们通过一个案例演示hibernate的使用。先在项目中导入hibernate所需的一系列jar包:
接着,在源代码根路径下创建并配置hibernate.cfg.xml文件:
<?xml version=\'1.0\' encoding=\'utf-8\'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:mysql://localhost:3306/b0307</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.username">root</property> <property name="connection.password">2018</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.current_session_context_class">thread</property> <mapping resource="com/itszt/domain/Emp.hbm.xml"></mapping> </session-factory> </hibernate-configuration>
然后,映射数据库中的一个表,并据此创建映射的类Emp,并配置该类基于hibernate的配置文件Emp.hbm.xml:
package com.itszt.domain; /** * 测试用的实体类 */ public class Emp { private int uid; private String name; public Emp(int uid, String name) { this.uid = uid; this.name = name; } @Override public String toString() { return "Emp{" + "uid=" + uid + ", name=\'" + name + \'\\\'\' + \'}\'; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Emp() { } }
Emp.hbm.xml配置文件:
<?xml version=\'1.0\' encoding=\'utf-8\'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.itszt.domain"> <class name="Emp" table="emp"> <id name="uid" column="uid"> <generator class="native"></generator> </id> <property name="name" column="name"></property> </class> <query name="queryTest1"> SELECT new Emp(uid,name) FROM Emp WHERE uid=? order by uid desc </query> <query name="queryTest2"> FROM Emp order by uid desc </query> <query name="queryTest3"> <![CDATA[ FROM Emp WHERE uid > ? and uid < ? ]]> </query> </hibernate-mapping>
测试类:
import com.itszt.domain.Emp; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; /** * 测试类 */ public class Test { public static void main(String[] args) { Configuration configuration=new Configuration().configure("hibernate.cfg.xml"); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Emp emp = new Emp(); emp.setUid(2); emp.setName("小马222"); Transaction transaction = session.beginTransaction(); //演示操作增删改查 // session.save(emp); // session.delete(emp); // session.update(emp); Emp emp1 = (Emp) session.get(Emp.class, 2); System.out.println("emp1 = " + emp1); transaction.commit(); session.close(); sessionFactory.close(); } }
此外,我们再创建一个工具类UtilHibernate,用来基于hibernate生成一个session:
import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * 工具类 */ public class UtilHibernate { private static Configuration configuration; private static SessionFactory sessionFactory; //什么是要重复调用的 //什么是要初始加载一次的 static { try { configuration=new Configuration().configure(); sessionFactory = configuration.buildSessionFactory(); //JVM的关闭钩子,在JVM退出时close我们的sessionFactory Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { super.run(); System.out.println("Execute Hook....."); if (sessionFactory != null) { sessionFactory.close(); } } }); } catch (HibernateException e) { throw new ExceptionInInitializerError("hibernate加载失败!!"); } } public static Session openNew(){ return sessionFactory.openSession(); } public static Session getCurrent(){ return sessionFactory.getCurrentSession(); } public static void release(Session session){ if (session != null) { if (session.isOpen()) { session.close(); } } } }
接下来,通过该工具类,再分别通过query查询,hql,以及criteria来测试各自的用法:
TestQuery.java import com.itszt.domain.Emp; import org.hibernate.Session; import org.hibernate.Transaction; /** * 测试查询 */ public class TestQuery { public static void main(String[] args) { Session session1 = UtilHibernate.getCurrent(); Transaction transaction = session1.beginTransaction(); //饿加载:只要查询,马上就执行sql然后把结果取回 Emp emp1= (Emp) session1.get(Emp.class, 2); System.out.println("emp1 = " + emp1); transaction.commit(); UtilHibernate.release(session1); Session session2 = UtilHibernate.getCurrent(); Transaction transaction2 = session2.beginTransaction(); //懒加载:等到使用该对象的时候再执行sql然后把结果取回 Emp emp2= (Emp) session2.load(Emp.class, 2); System.out.println("emp2 = " + emp2); transaction2.commit(); UtilHibernate.release(session2); //退出JVM。。。 System.exit(0); } } ----------------------------------------------------- TestHQL.java import com.itszt.domain.Emp; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import java.util.Arrays; import java.util.List; /** * HQL查询语言 */ public class TestHQL { //:role形式的参数设置查询 public static void main(String[] args) { Session session = UtilHibernate.getCurrent(); Transaction transaction = session.beginTransaction(); Query query = session.createQuery("SELECT new Emp(uid,name) FROM Emp WHERE uid=:uid AND name=:name"); // query.setParameter("uid",8); // query.setParameter("name","测试角色2222222"); Emp emp=new Emp(2,"小马222"); query.setProperties(emp); Object result = query.uniqueResult(); System.out.println("result = " + result); transaction.commit(); UtilHibernate.release(session); System.exit(0); } public static void main4(String[] args) { Session session = UtilHibernate.getCurrent(); Transaction transaction = session.beginTransaction(); Query query = session.createQuery("SELECT new Emp(uid,name) FROM Emp WHERE uid=?"); query.setParameter(0,2); Emp emp= (Emp) query.uniqueResult(); System.out.println("emp = " + emp); transaction.commit(); UtilHibernate.release(session); System.exit(0); } //查询其中的几列 public static void main3(String[] args) { Session session = UtilHibernate.getCurrent(); Transaction transaction = session.beginTransaction(); Query query = session.createQuery("SELECT uid,name FROM Emp WHERE uid=?"); query.setParameter(0,2); Object[] results= (Object[]) query.uniqueResult(); System.out.println("results = " + Arrays.toString(results)); Query query1 = session.createQuery("SELECT COUNT (*) FROM Emp"); Long num = (Long) query1.uniqueResult(); System.out.println("num = " + num); transaction.commit(); UtilHibernate.release(session); System.exit(0); } //查询单个数据,设置查询条件,返回单个对象 public static void main2(String[] args) { Session session = UtilHibernate.getCurrent(); Transaction transaction = session.beginTransaction(); Query query = session.createQuery("FROM Emp WHERE uid=?"); query.setParameter(0,2); Emp emp= (Emp) query.uniqueResult(); System.out.println("emp = " + emp); transaction.commit(); UtilHibernate.release(session); System.exit(0); } //查询全部数据 ,返回一个list public static void main1(String[] args) { Session session = UtilHibernate.getCurrent(); Transaction transaction = session.beginTransaction(); Query query = session.createQuery("FROM Emp"); List<Emp> list = query.list(); System.out.println("list = " + list); transaction.commit(); UtilHibernate.release(session); System.exit(0); } } -------------------------------------------- TestHQL2.java import com.itszt.domain.Emp; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.Transaction; import java.util.Arrays; import java.util.List; /** * HQL查询语言2 */ @SuppressWarnings("ALL") public class TestHQL2 { //原生SQL查询 public static void main(String[] args) { Session session = UtilHibernate.getCurrent(); Transaction transaction = session.beginTransaction(); SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM emp"); sqlQuery.addEntity(Emp.class); List<Emp> emp = (List<Emp>) sqlQuery.list(); System.out.println("emp = " + emp); transaction.commit(); UtilHibernate.release(session); System.exit(0); } //原生SQL查询 public static void main2(String[] args) { Session session = UtilHibernate.getCurrent(); Transaction transaction = session.beginTransaction(); SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM emp"); List<Object[]> list = sqlQuery.list(); for (Object[] o : list) { System.out.println("o = " + Arrays.toString(o)); } transaction.commit(); UtilHibernate.release(session); System.exit(0); } //将SQL写在配置文件里 public static void main1(String[] args) { Session session = UtilHibernate.getCurrent(); Transaction transaction = session.beginTransaction(); Query query = session.getNamedQuery("queryTest1"); query.setParameter(0,8); Emp emp= (Emp) query.uniqueResult(); System.out.println("emp = " + emp); Query queryTest2 = session.getNamedQuery("queryTest2"); List list = queryTest2.list(); System.out.println("list = " + list); Query queryTest3 = session.getNamedQuery("queryTest3"); queryTest3.setParameter(0,2); queryTest3.setParameter(1,6); List list2 = queryTest3.list(); System.out.println("list2 = " + list2); transaction.commit(); UtilHibernate.release(session); System.exit(0); } } ------------------------------------------------------ TestCriteria.java import com.itszt.domain.Emp; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import java.util.List; /** * 测试Criteria方式 */ public class TestCriteria { public static void main(String[] args) { Session session = UtilHibernate.getCurrent(); Transaction transaction = session.beginTransaction(); Criteria criteria = session.createCriteria(Emp.class); //基本比较 //criteria.add(Restrictions.lt("uid",5)); // criteria.add(Restrictions.lt("uid",3)); // criteria.add(Restrictions.gt("uid",1)); //分页--------- criteria.setFirstResult(0); criteria.setMaxResults(5); //分页--------- List<Emp> emps= criteria.list(); System.out.println("emps = " + emps); //聚合 /*criteria.setProjection(Projections.sum("uid")); Long result= (Long) criteria.uniqueResult(); System.out.println("result = " + result);*/ transaction.commit(); UtilHibernate.release(session); System.exit(0); } public static void main1(String[] args) { Session session = UtilHibernate.getCurrent(); Transaction transaction = session.beginTransaction(); Criteria criteria = session.createCriteria(Emp.class); criteria.add(Restrictions.eq("uid",6)); Emp emp = (Emp) criteria.uniqueResult(); System.out.println("emp = " + emp); transaction.commit(); UtilHibernate.release(session); System.exit(0); } }
以上是关于hibernate使用的主要内容,如果未能解决你的问题,请参考以下文章
使用反射在外部JAR / CLASS上调用包含Hibernate事务的方法(Java EE)
hibernate在使用getCurrentSession时提示no session found for current thread
Hibernate CriteriaQuery where - ManyToOne 字段