三大框架之hibernate入门

时间:2021-04-20 08:52:37
hibernate入门
 
1、orm
     hibernate是一个经典的开源的orm[数据访问中间件]框架
          ORM( Object Relation Mapping)对象关系映射
     通过 对象模型 操作 数据库关系模型
hibernate处于项目的持久层位置,因此又称为持久层框架
 
2、hibernate核心组件
     
     SessionFactory [整个数据库的操作] 重量级组件
     Session[对数据库的一次业务操作] -- 轻量级组件
 
3、hibernate配置
     配置SessionFactory
 
4、使用hibernate开发一个APP
 
在导好jar包后:
     a.配置hibernate.cfg.xml:三大框架之hibernate入门
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<!--SQL dialect 方言-->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!--Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!--Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<mapping resource="com/it/bean/UserInfo.hbm.xml"/>
</session-factory>
</hibernate-configuration>
 
 SessionFactory  ---  关联  xxx.hbm.xml
UserInfo.hbm.xml的配置:
 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.it.bean">
<class name="UserInfo" table="userinfo">
<id name="user_id" column="user_id">
<!-- 主键生成策略 -->
<generator class="assigned"></generator>
</id>
<property name="user_name" column="user_name"></property>
<property name="user_sex" column="user_sex"></property>
<property name="user_birth" column="user_birth"></property>
<property name="user_addr" column="user_addr"></property>
<property name="user_pwd" column="user_pwd"></property>
</class>
</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):
 package com.it.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import com.it.dao.util.SessionFactoryUtils;
/**
* 基础DAO
* @author xj
*
*/
public class BaseDAO <T>{
/**
* 查询集合--全部
*/
public List<T> find(String hql){
Session session =null;
//事务
Transaction tx = null;
List<T> list =null;
try {
//这里将创建SessionFactory写成了方法(工具类)--创建SessionFactory并得到Session
session=SessionFactoryUtils.getSessionFactory().getCurrentSession();
//开启事务
tx=session.beginTransaction();
//查询Java bean UserInfo--对象这里hql是查询语句:eg:from UserInfo(UserInfo-->是java bean里的对象)
Query query = session.createQuery(hql);
list = query.list();
//提交
tx.commit();
} catch (Exception e) {
e.printStackTrace();
//事务回滚
tx.rollback();
}
return list;
} /**
* 查询带参数
*/
public List<T> find(String hql,String ...params){
Session session =null;
//事务
Transaction tx = null;
List<T> list =null;
try {
session=SessionFactoryUtils.getSessionFactory().getCurrentSession();
//开启事务
tx=session.beginTransaction();
//查询Java bean UserInfo--对象
Query query = session.createQuery(hql);
//给参数赋值
for (int i = 0; i < params.length; i++) {
query.setString(i, params[i]);
}
list = query.list();
//提交
tx.commit();
} catch (Exception e) {
e.printStackTrace();
//事务回滚
tx.rollback();
}
return list;
} }
/**
* 添加
* @param obj
*/
public void add(Object obj){
Session session =null;
Transaction tx = null;
try {
//
session=SessionFactoryUtils.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
//操作
session.save(obj);
//提交
tx.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
//事务回滚
tx.rollback();
System.out.println("--我回滚啦---");
}
} /**
* 按对象删除
*/
public void del(Object obj){
Session session =null;
Transaction tx = null;
try {
//
session=SessionFactoryUtils.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
//操作
session.delete(obj);
//提交
tx.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
//事务回滚
tx.rollback();
System.out.println("--我回滚啦---");
}
}
/**
* 按编号删除
*/
public void delete(Class<T> clz, String OID){
Session session =null;
Transaction tx = null;
//通过给的id来查询该id的对象
Object o=get(clz,OID);
try {
//
session=SessionFactoryUtils.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
//操作
session.delete(o);
//提交
tx.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
//事务回滚
tx.rollback();
System.out.println("--我回滚啦---");
}
} /**
* 修改
* @param obj
*/
public void upd(Object obj){
Session session =null;
Transaction tx = null;
try {
//得到SessionFactory
session=SessionFactoryUtils.getSessionFactory().getCurrentSession();
//开启事务
tx=session.beginTransaction();
//操作
session.update(obj);
//提交
tx.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
//事务回滚
tx.rollback();
System.out.println("--我回滚啦---");
}
} /**
* 查询
*/
public T get(Class<T> clz, String OID){
Session session =null;
Transaction tx = null;
T t=null;
try {
//
session=SessionFactoryUtils.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
//操作
t = (T) session.get(getClass(), OID);
//提交
tx.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
//事务回滚
tx.rollback();
System.out.println("--我回滚啦---");
}
return t;
}
hibernate导的包:三大框架之hibernate入门三大框架之hibernate入门三大框架之hibernate入门三大框架之hibernate入门