Hibernate 实现原理

[size=medium][color=green][b]整体流程
1:通过configuration来读cfg.xml文件
2:得到SessionFactory 工厂
3:通过SessionFactory 工厂来创建Session实例
4:通过Session打开事务
5:通过session的api操作数据库
6:事务提交
7:关闭连接

为什么要用:
1. 对JDBC访问数据库的代码做了封装,大大简化了数据访问层繁琐的重复性代码。
2. Hibernate是一个基于JDBC的主流持久化框架,是一个优秀的ORM实现。他很大程度的简化DAO层的编码工作。
3. hibernate使用Java反射机制,而不是字节码增强程序来实现透明性。
4. hibernate的性能非常好,因为它是个轻量级框架。映射的灵活性很出色。它支持各种关系数据库,从一对一到多对多的各种复杂关系。
[/b][/color][/size]


[size=medium][color=red][b]两种取得session方法:[/b][/color][/size]
openSession和getCurrentSession区别
openSession:永远创建新的session 需手动close,事务提交不会自动close
getCurrentSession:事务没提交之前。在上下文找,有可能返回旧的session,事务提交了,会得到新的session。事务提交,session自动close
上下文,在配置文件指定:
<property name="current_session_context_class">thread</property>
jta | thread | managed | custom.Class 
thread常用—》必须指明current_session_context_class,否则抛异常

[size=medium][color=green][b]a.sessionFactory.openSession();[/b][/color][/size]

sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession(); //创建新的session对象
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
session.close() ; //关闭session对象



[size=medium][b][color=green]b.sessionFactory.getCurrentSession();[/color][/b][/size]

sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession(); //获取当前"上下文"中的session对象
session.beginTransaction();
session.save(t);
Session session2 = sessionFactory.getCurrentSession();
System.out.println(session == session2); //true
session.getTransaction().commit(); //事务提交自动关闭该session
System.out.println(session == session2); //false




一、没有通过applicationContext.xml配置文件加载hibernate.cfg.xml,而是通过
自定义的类HibernateUtil.java创建sessionFactory对象


1.TeamDaoHibernate
package com.org.momo.dao.hibernateTemplate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.org.momo.bean.PageInfo;
import com.org.momo.bean.Team;
import com.org.momo.dao.TeamDao;
import com.org.momo.util.HibernateUtil;

public class TeamDaoHibernate implements TeamDao {
private SessionFactory sessionFactory;

public TeamDaoHibernatenotused() {
sessionFactory = HibernateUtil.getSessionFactory();
}

public void insert(Team team) throws Exception {
Session session = sessionFactory.openSession();

Transaction transaction = session.beginTransaction();
session.save(team);
transaction.commit();

session.close() ;
}

public void deleteById(Integer id) throws Exception {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

String hql = "delete from Team where id=?";
Query query = session.createQuery(hql);
query.setInteger(0, id);
query.executeUpdate();

transaction.commit();
session.close();
}

public void update(Team team) throws Exception {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

session.merge(team);

transaction.commit();
session.close();
}

public List<Team> findAll() throws Exception {
List<Team> teams = null;

Session session = sessionFactory.openSession();

Query query = session.createQuery("from Team");
teams = query.list();

session.close();

return teams;
}

public Team findById(Integer id) throws Exception {
Team team = null;

Session session = sessionFactory.openSession();
Query query = session.createQuery("from Team where id=?");
query.setInteger(0, id);
team = (Team)query.uniqueResult();
session.close();

return team;
}

public List<Team> findAllPage(PageInfo pageInfo) throws Exception {
List<Team> teams = null;

Session session = sessionFactory.openSession();

Query queryTotal = session.createQuery("select count(id) from Team");
int rowCount = ((Long)queryTotal.uniqueResult()).intValue() ; //先转换为Long 在转换为int
int pageTotal = rowCount/pageInfo.getPageRows();
if(rowCount%pageInfo.getPageRows() > 0) {
pageTotal++;
}
pageInfo.setPageTotal(pageTotal);

Query query = session.createQuery("from Team");
query.setFirstResult(pageInfo.getPageRows()*(pageInfo.getCurrentPage()-1));
query.setMaxResults(pageInfo.getPageRows());
teams = query.list();

session.close();

return teams;
}

}



2.HibernateUtil.java

package com.org.momo.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;


public class HibernateUtil {
private static final SessionFactory sessionFactory;
static{
try{
//初始化hibernate.cfg.xml配置,建立数据库连接
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}catch(Exception e){
e.printStackTrace() ;
throw new ExceptionInInitializerError(e) ;
}
}

public static SessionFactory getSessionFactory(){
return sessionFactory ;
}
}



二、通过配置Spring的applicationContext.xml文件加载,spring对Hibernate的支持(HibernateTemplate)

1.applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="teamService" class="com.org.momo.service.impl.TeamServiceImpl">
<property name="teamDao" ref="teamDao"></property>
</bean>
<bean id="adminService" class="com.org.momo.service.impl.AdminServiceImpl">
<property name="adminDao" ref="adminDao"></property>
</bean>
<bean id="logService" class="com.org.momo.service.impl.LogServiceImpl">
<property name="logDao" ref="logDao"></property>
</bean>
<bean id="studentService" class="com.org.momo.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>


<bean id="teamDao" class="com.org.momo.dao.hibernateTemplate.TeamDaoHibernateTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="adminDao" class="com.org.momo.dao.hibernateTemplate.AdminDaoHibernateTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="logDao" class="com.org.momo.dao.hibernateTemplate.LogDaoHibernateTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>
<bean id="studentDao" class="com.org.momo.dao.hibernateTemplate.StudentDaoHibernateTemplate">
<property name="hibernateTemplate" ref="hibernateTemplate"/>
</bean>


<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
</bean>
</beans>


2.HibernateTemplate


package com.org.momo.dao.hibernateTemplate;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.org.momo.bean.PageInfo;
import com.org.momo.bean.Team;
import com.org.momo.dao.TeamDao;

public class TeamDaoHibernateTemplate extends HibernateDaoSupport implements TeamDao {

public void deleteById(Integer id) throws Exception {
Team team = this.getHibernateTemplate().load(Team.class, id) ;
this.getHibernateTemplate().delete(team) ;
}

public List<Team> findAll() throws Exception {
return this.getHibernateTemplate().loadAll(Team.class);
}

public Team findById(Integer id) throws Exception {
List<Team> teams = this.getHibernateTemplate().find("from Team where id=?",id) ;
if(!teams.isEmpty()){
return teams.get(0) ;
}else{
return null;
}
}

public void insert(Team team) throws Exception {
this.getHibernateTemplate().save(team) ;
}

public void update(Team team) throws Exception {
this.getHibernateTemplate().update(team);
}

public List<Team> findAllPage(final PageInfo pageInfo) throws Exception {
List<Team> teams = null;

int rowTotal = ((Long)this.getHibernateTemplate().find("select count(id) from Team").get(0)).intValue();
int pageTotal = rowTotal/pageInfo.getPageRows();
if(rowTotal%pageInfo.getPageRows() > 0) {
pageTotal++;
}
pageInfo.setPageTotal(pageTotal);

teams = this.getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query = session.createQuery("from Team");
query.setFirstResult(pageInfo.getPageRows()*(pageInfo.getCurrentPage()-1));
query.setMaxResults(pageInfo.getPageRows());
return query.list();
}

});

return teams;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值