hibernate的Sessionfactory.getCurrentSession详解和在项目中常用方法

本文详细介绍了Hibernate的SessionFactory.getCurrentSession与openSession的区别,强调了getCurrentSession在事务管理和线程绑定上的特性。此外,还列举了Session常用方法,包括开始事务、取消查询、清除缓存、创建Criteria查询等,并提供了如何根据实体名称和ID获取对象的实例代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sessionfactory.getCurrentSession与 openSession() 的区别

1. getCurrentSession创建的session会和绑定到当前线程,openSession不会。

2. getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,openSession必须手动关闭。

这里getCurrentSession本地事务(本地事务:jdbc)要在配置文件里进行如下设置

    * 如果使用的是本地事务(jdbc事务)
 <propertyname="hibernate.current_session_context_class">thread</property>
 *
如果使用的是全局事务(jta事务)
 <propertyname="hibernate.current_session_context_class">jta</property> 

继承Session 方法及说明

1 TransactionbeginTransaction()

开始工作单位,并返回关联事务对象。

2 voidcancelQuery()

取消当前的查询执行。

3 void clear()

完全清除该会话。

4 Connectionclose()

通过释放和清理 JDBC 连接以结束该会话。

5 Criteria createCriteria(ClasspersistentClass)

为给定的实体类或实体类的超类创建一个新的 Criteria 实例。

6 CriteriacreateCriteria(String entityName)

为给定的实体名称创建一个新的 Criteria 实例。

7 SerializablegetIdentifier(Objectobject)

返回与给定实体相关联的会话的标识符值。

8 QuerycreateFilter(Object collection, String queryString)

为给定的集合和过滤字符创建查询的新实例。

9 QuerycreateQuery(String queryString)

为给定的 HQL 查询字符创建查询的新实例。

10 SQLQuerycreateSQLQuery(String queryString)

为给定的 SQL 查询字符串创建 SQLQuery 的新实例。

11 void delete(Objectobject)

从数据存储中删除持久化实例。

12 void delete(String entityName, Objectobject)

从数据存储中删除持久化实例。

13 Session get(String entityName,Serializable id)

返回给定命名的且带有给定标识符或 null 的持久化实例(若无该种持久化实例)。

14SessionFactory getSessionFactory()

获取创建该会话的 session 工厂。

15 voidrefresh(Objectobject)

从基本数据库中重新读取给定实例的状态。

16 TransactiongetTransaction()

获取与该 session 关联的事务实例。

17booleanisConnected()

检查当前 session 是否连接。

18boolean isDirty()

session 中是否包含必须与数据库同步的变化?

19boolean isOpen()

检查该 session 是否仍处于开启状态。

20 Serializablesave(Objectobject)

先分配一个生成的标识,以保持给定的瞬时状态实例。

21 voidsaveOrUpdate(Objectobject)

保存(对象)或更新(对象)给定的实例。

22 void update(Objectobject)

更新带有标识符且是给定的处于脱管状态的实例的持久化实例。

23 void update(String entityName, Objectobject)

更新带有标识符且是给定的处于脱管状态的实例的持久化实例。


实例

import java.text.SimpleDateFormat;
import java.util.Date;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import com.ztkj.oes.dao.OneChoiceDao;
import com.ztkj.oes.model.OneChoiceQuestions;
import com.ztkj.oes.utils.AbstractManager;
import com.ztkj.oes.utils.PageUtil;

/**
 * 单选题持久层实例化
 * @author huangyu
 * @	2016-9-11
 */
@Repository
public class OneChoiceDaoImpl extends AbstractManager implements OneChoiceDao {

	protected SessionFactory sessionFactory;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	/**
	 * 条件分页查询
	 * @param Date beginDate 开始日期
	 * @param Date endDate   结束日期
	 * @param String content   部分题目内容
	 * @param int belongsChapter  所属章节
	 * @param int category  题目类型
	 * @return PageUtil pageUtil 分页对象
	 */
	public PageUtil conditionFind(Date beginDate, Date endDate, String content,
			int belongsChapter, int category) {
		StringBuffer hql = new StringBuffer();
		hql.append("select p from OneChoiceQuestions p where 1=1");
		if(beginDate != null && endDate != null){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String beginDate1 = sdf.format(beginDate);
			String endDate1 = sdf.format(endDate);
			hql.append(" and (p.inputTime between '").append(beginDate1).append("' and '").append(endDate1).append("')");
		}
		if(content != null){
			//模糊查询
			hql.append(" and p.content like '%").append(content).append("%'");
		}
		if(belongsChapter != -1){
			hql.append(" and p.belongsChapter = ").append(belongsChapter);
		}
		if(category != -1){
			hql.append(" and p.category = ").append(category);
		}
		return searchPaginate(hql.toString());
	}

	/**
	 * 条件统计
	 * @param Date beginDate 开始日期
	 * @param Date endDate   结束日期
	 * @param String content   部分题目内容
	 * @param int belongsChapter  所属章节
	 * @param int category  题目类型
	 * @return long 分页对象总条数
	 */
	public long conditionTotal(Date beginDate, Date endDate,
			String content, int belongsChapter, int category) {
		StringBuffer hql = new StringBuffer();
		hql.append("select count(*) from OneChoiceQuestions u where 1=1");
		if(beginDate != null && endDate != null){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String beginDate1 = sdf.format(beginDate);
			String endDate1 = sdf.format(endDate);
			hql.append(" and (u.inputTime between '").append(beginDate1).append("' and '").append(endDate1).append("')");
		}
		if(content != null){
			hql.append(" and u.content like '%").append(content).append("%'");
		}
		if(belongsChapter != -1){
			hql.append(" and u.belongsChapter = ").append(belongsChapter);
		}
		if(category != -1){
			hql.append(" and u.category = ").append(category);
		}
		return ((Long)sessionFactory.getCurrentSession().createQuery(hql.toString()).uniqueResult()).intValue();
	}

	/**
	 * 批量是删除单项选择题
	 * @param long[] idArray 题目id数组
	 */
	public void deleteOneChoiceQuestions(long[] idArray) {
		OneChoiceQuestions oneChoiceQuestions = new OneChoiceQuestions();
		for(int i=0;i<idArray.length;i++){
			oneChoiceQuestions = (OneChoiceQuestions)sessionFactory.getCurrentSession().get(OneChoiceQuestions.class, idArray[i]);
			sessionFactory.getCurrentSession().delete(oneChoiceQuestions);
		}
	}

	/**
	 * 删除指定的单项选择题
	 * @param long id 单项选择题ID
	 */
	public void deleteOneChoiceQuestions(long id) {
		sessionFactory.getCurrentSession().delete(
				(OneChoiceQuestions)sessionFactory.getCurrentSession().get(OneChoiceQuestions.class, id)
				);
	}

	/**
	 * 按题目id查找题目
	 * @param id
	 * @return OneChoiceQuestions oneChoiceQuestions题目对象
	 */
	public OneChoiceQuestions findById(long id) {
		return (OneChoiceQuestions)sessionFactory.getCurrentSession().get(OneChoiceQuestions.class, id);
	}

	/**
	 * 增加单项选择题
	 * @param OneChoiceQuestions oneChoiceQuestions 单项选择题对象
	 */
	public void saveOneChoiceQuerstion(OneChoiceQuestions oneChoiceQuestions) {
		sessionFactory.getCurrentSession().save(oneChoiceQuestions);
	}

	/**
	 * 修改指定的单项选择题
	 * @param OneChoiceQuestions oneChoiceQuestions 单项选择题对象
	 */
	public void updateOneChoiceQuestions(OneChoiceQuestions oneChoiceQuestions) {
		sessionFactory.getCurrentSession().update(oneChoiceQuestions);
	}
	
}

根据String 查询拿到一个对象,代码如下

	/**
	 * 根据用户身份证号码查找指定的用户
	 * @param String idCardNo  用户身份证号码
	 * @return User user 返回指定的用户
	 */
	public User findUserByIdCarNo(String idCardNo){
		StringBuffer hql = new StringBuffer();
		hql.append("select u from User u where u.idCardNo = '").append(idCardNo).append("'");
		User user= (User)sessionFactory.getCurrentSession().createQuery(hql.toString()).uniqueResult();
		return user;
	}
配置文件.xml,及配置的依赖关系

applicationContext-dao.xml

<bean id="oneChoiceDao" class="com.ztkj.oes.dao.impl.OneChoiceDaoImpl">
     <property name="sessionFactory" ref="sessionFactory"></property>
   </bean>
applicationContext-commons.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" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="   
           http://www.springframework.org/schema/beans   
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd   
           http://www.springframework.org/schema/context   
           http://www.springframework.org/schema/context/spring-context-3.2.xsd  
           http://www.springframework.org/schema/mvc   
           http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
           
  
	
       <!-- 使用c3p0实现datasource,连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl"
			value="jdbc:mysql://localhost:3306/oes?useUnicode=true&characterEncoding=UTF-8" />
		<property name="user" value="root" />
		<property name="password" value="root_123" />
		<property name="minPoolSize" value="15" />
		<property name="maxPoolSize" value="50" />
		<property name="initialPoolSize" value="15" />
	</bean>
           
	<!-- 创建sessioFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name ="dataSource" ref="dataSource"/>
		<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
	</bean>

	
	<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- 哪些类的哪些方法要使用事务 -->
	<aop:config  expose-proxy="true">
		<aop:pointcut id="allServiceMethod" expression="execution(* com.ztkj.oes.service.*.*(..))" />
		<aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" />
	</aop:config>
	
		<!-- 事务的传播特性 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>
	
</beans>

hibernate.cfg.xml

<!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>	
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="show_sql">true</property>
		<property name="hibernate.hbm2ddl.auto">update</property>
		<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
		<!-- 映射文件的配置 -->
		<mapping class="com.ztkj.oes.model.User"/>
		<mapping class="com.ztkj.oes.model.OneChoiceQuestions"/>
		<mapping class="com.ztkj.oes.model.MultipleChoiceQuestTions"/>
		<mapping class="com.ztkj.oes.model.JudgmentQuestion"/>
		<mapping class="com.ztkj.oes.model.InterviewQuestions"/>
		<mapping class="com.ztkj.oes.model.Payment"/>
		<mapping class="com.ztkj.oes.model.Resource"/>
	</session-factory>
</hibernate-configuration>
web.xml

<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext-*.xml</param-value>
	</context-param>
	
     <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值