hibernate入门
1、orm
hibernate是一个经典的开源的orm[数据访问中间件]框架
ORM( Object Relation Mapping)对象关系映射
通过 对象模型 操作 数据库关系模型
hibernate处于项目的持久层位置,因此又称为持久层框架
2、hibernate核心组件
SessionFactory [整个数据库的操作] 重量级组件
Session[对数据库的一次业务操作] -- 轻量级组件
3、hibernate配置
配置SessionFactory
4、使用hibernate开发一个APP
在导好jar包后:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <!--Database connection settings --> 8 <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> 10 <property name="connection.username">scott</property> 11 <property name="connection.password">tiger</property> 12 <!--SQL dialect 方言--> 13 <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> 14 <!--Enable Hibernate's automatic session context management --> 15 <property name="current_session_context_class">thread</property> 16 <!--Echo all executed SQL to stdout --> 17 <property name="show_sql">true</property> 18 <mapping resource="com/it/bean/UserInfo.hbm.xml"/> 19 </session-factory> 20 </hibernate-configuration>
SessionFactory --- 关联 xxx.hbm.xml
UserInfo.hbm.xml的配置:
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping package="com.it.bean"> 6 <class name="UserInfo" table="userinfo"> 7 <id name="user_id" column="user_id"> 8 <!-- 主键生成策略 --> 9 <generator class="assigned"></generator> 10 </id> 11 <property name="user_name" column="user_name"></property> 12 <property name="user_sex" column="user_sex"></property> 13 <property name="user_birth" column="user_birth"></property> 14 <property name="user_addr" column="user_addr"></property> 15 <property name="user_pwd" column="user_pwd"></property> 16 </class> 17 </hibernate-mapping>
补充:
主键生成策略:
-
Assigned:主键由外部程序生成,无需Hibernate干预。
-
identity:采用数据库提供的主键生成机制,如MySql、DB2、SqlServer的自增主键。
-
sequence:使用数据库的sequence机制。
-
hilo:通过hi/lo 算法实现的主键生成机制,需要额外的数据库表保存主键生成历史状态。
-
seqhilo:与hilo 类似,通过hi/lo 算法实现的主键生成机制,只是主键历史状态保存在Sequence中,适用于支持Sequence的数据库,如Oracle。
-
increment:主键按数值顺序递增。此方式的实现机制为在当前应用实例中维持一个变量,以保存着当前的最大值,之后每次需要生成主键的时候将此值加1作为主键。这种方式可能产生的问题是:如果当前有多个实例访问同一个数据库,那么由于各个实例各自维护主键状态,不同实例可能生成同样的主键,从而造成主键重复异常。因此,如果同一数据库有多个实例访问,此方式必须避免使用。
-
native:由Hibernate根据底层数据库定义自行判断采用identity、hilo、sequence其中一种作为主键生成方式。
-
foreign:使用外部表的字段作为主键。
-
uuid.hex:由Hibernate基于128 位唯一值产生算法,根据IP、当前时间、JVM启动时间、内部自增量生成16 进制数值(编码后以长度32 的字符串表示)作为主键,该方法提供了最好的数据库插入性能和数据库平台适应性。
-
uuid.string:与uuid.hex 类似,只是生成的主键未进行编码(长度16),在某些数据库中可能出现问题(如PostgreSQL)。
b、创建sessionFactory
SessionFactory sessionFactory=(SessionFactory) new Configuration().configure().buildSessionFactory();
c.创建Session
Session session=sessionFactory .getCurrentSession();
d.创建Transaction
//创建事务并开启事务
Transaction tx = session.beginTransaction();
e.开启事务
f.执行操作--业务操作
g.提交事务
tx.commit();
h.异常处理块,事务回滚
在try catch异常处理后,tx.rollback;
完整代码(basedao):
1 package com.it.dao; 2 import java.util.List; 3 import org.hibernate.Query; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.Transaction; 6 import org.hibernate.cfg.Configuration; 7 import org.hibernate.classic.Session; 8 import com.it.dao.util.SessionFactoryUtils; 9 /** 10 * 基础DAO 11 * @author xj 12 * 13 */ 14 public class BaseDAO <T>{ 15 /** 16 * 查询集合--全部 17 */ 18 public List<T> find(String hql){ 19 Session session =null; 20 //事务 21 Transaction tx = null; 22 List<T> list =null; 23 try { 24 //这里将创建SessionFactory写成了方法(工具类)--创建SessionFactory并得到Session 25 session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 26 //开启事务 27 tx=session.beginTransaction(); 28 //查询Java bean UserInfo--对象这里hql是查询语句:eg:from UserInfo(UserInfo-->是java bean里的对象) 29 Query query = session.createQuery(hql); 30 list = query.list(); 31 //提交 32 tx.commit(); 33 } catch (Exception e) { 34 e.printStackTrace(); 35 //事务回滚 36 tx.rollback(); 37 } 38 return list; 39 } 40 41 /** 42 * 查询带参数 43 */ 44 public List<T> find(String hql,String ...params){ 45 Session session =null; 46 //事务 47 Transaction tx = null; 48 List<T> list =null; 49 try { 50 session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 51 //开启事务 52 tx=session.beginTransaction(); 53 //查询Java bean UserInfo--对象 54 Query query = session.createQuery(hql); 55 //给参数赋值 56 for (int i = 0; i < params.length; i++) { 57 query.setString(i, params[i]); 58 } 59 list = query.list(); 60 //提交 61 tx.commit(); 62 } catch (Exception e) { 63 e.printStackTrace(); 64 //事务回滚 65 tx.rollback(); 66 } 67 return list; 68 } 69 70 } 71 /** 72 * 添加 73 * @param obj 74 */ 75 public void add(Object obj){ 76 Session session =null; 77 Transaction tx = null; 78 try { 79 // 80 session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 81 tx=session.beginTransaction(); 82 //操作 83 session.save(obj); 84 //提交 85 tx.commit(); 86 } catch (Exception e) { 87 // TODO: handle exception 88 e.printStackTrace(); 89 //事务回滚 90 tx.rollback(); 91 System.out.println("--我回滚啦---"); 92 } 93 } 94 95 /** 96 * 按对象删除 97 */ 98 public void del(Object obj){ 99 Session session =null; 100 Transaction tx = null; 101 try { 102 // 103 session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 104 tx=session.beginTransaction(); 105 //操作 106 session.delete(obj); 107 //提交 108 tx.commit(); 109 } catch (Exception e) { 110 // TODO: handle exception 111 e.printStackTrace(); 112 //事务回滚 113 tx.rollback(); 114 System.out.println("--我回滚啦---"); 115 } 116 } 117 /** 118 * 按编号删除 119 */ 120 public void delete(Class<T> clz, String OID){ 121 Session session =null; 122 Transaction tx = null; 123 //通过给的id来查询该id的对象 124 Object o=get(clz,OID); 125 try { 126 // 127 session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 128 tx=session.beginTransaction(); 129 //操作 130 session.delete(o); 131 //提交 132 tx.commit(); 133 } catch (Exception e) { 134 // TODO: handle exception 135 e.printStackTrace(); 136 //事务回滚 137 tx.rollback(); 138 System.out.println("--我回滚啦---"); 139 } 140 } 141 142 /** 143 * 修改 144 * @param obj 145 */ 146 public void upd(Object obj){ 147 Session session =null; 148 Transaction tx = null; 149 try { 150 //得到SessionFactory 151 session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 152 //开启事务 153 tx=session.beginTransaction(); 154 //操作 155 session.update(obj); 156 //提交 157 tx.commit(); 158 } catch (Exception e) { 159 // TODO: handle exception 160 e.printStackTrace(); 161 //事务回滚 162 tx.rollback(); 163 System.out.println("--我回滚啦---"); 164 } 165 } 166 167 /** 168 * 查询 169 */ 170 public T get(Class<T> clz, String OID){ 171 Session session =null; 172 Transaction tx = null; 173 T t=null; 174 try { 175 // 176 session=SessionFactoryUtils.getSessionFactory().getCurrentSession(); 177 tx=session.beginTransaction(); 178 //操作 179 t = (T) session.get(getClass(), OID); 180 //提交 181 tx.commit(); 182 } catch (Exception e) { 183 // TODO: handle exception 184 e.printStackTrace(); 185 //事务回滚 186 tx.rollback(); 187 System.out.println("--我回滚啦---"); 188 } 189 return t; 190 } 191
浙公网安备 33010602011771号