org.hibernate的get与load.SessionFactory.getCurrentSession() 如何解决

sessionFactory.getCurrentSession()说明_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
sessionFactory.getCurrentSession()说明
&&hibernate spring
你可能喜欢getCurrentSession方法为什么报错了!!-CSDN论坛
getCurrentSession方法为什么报错了!!
在整理springMVC+hibernate。
配置好了,在dao中使用注入:
private&SessionFactory&sessionF
protected&Session&getSession()&{
System.out.println(sessionFactory);
return&sessionFactory.getCurrentSession();
这里的return报错了:
java.lang.NoSuchMethodError:&org.hibernate.SessionFactory.getCurrentSession()Lorg/hibernate/classic/S
之前用的ssh中没问题啊,是不是因为我包换了原来ssh的是hibernate3的&现在换成了4的。
如果4不支持的话,我想在dao中使用hql语句。怎么处理啊!!!
下面是我的代码:
package&com.jd.oa.
import&java.util.L
public&interface&BaseDao&T&&{
&*&返回所有对象集合
&*&@return
List&T&&findAll();
&*&根据id数据返回对象集合
&*&@param&id
&*&@return
List&T&&findByIds(String[]&ids);
&*&根据hql放回所有符合条件的对象集合
&*&@param&hql
&*&@return
List&T&&findAll(String&hql,List&Object&&params);
&*&根据分页信息返回所有的对象集合
&*&@param&page
&*&@param&pageSize
&*&@return
List&T&&findByPage(int&page,int&pageSize);
&*&根据分页信息返回所有的对象集合
&*&@param&hql 传入的hql语句
&*&@param&page
&*&@param&pageSize
&*&@return
List&T&&findByPage(String&hql,List&Object&&params,&int&page,&int&pageSize);
&*&根据id返回对象
&*&@param&id
&*&@return
T&findById(String&id);
&*&更具用户的属性返回对象
&*&@param&proName
&*&@param&proValue
&*&@return
List&T&&findByPropertiy(String&proName,String&proValue);
&*&计算记录数量
&*&@return
long&count();
&*&根据hql语句,计算条件记录数量
&*&@return
long&count(String&hql,List&Object&&params);
&*&根据id删除对象
&*&@param&id
void&delete(String&id);
&*&数组删除
&*&@param&ids
void&deleteByIds(String[]&ids);
&*&更新数据库中的对象信息
&*&@param&entity
void&update(T&entity);
&*&向数据库中添加对象记录
&*&@param&entity
void&add(T&entity);
package&com.jd.oa.
import&java.lang.reflect.ParameterizedT
import&java.util.C
import&java.util.L
import&javax.annotation.R
import&org.hibernate.Q
import&org.hibernate.S
import&org.hibernate.SessionF
@SuppressWarnings("unchecked")
public&class&BaseDaoImpl&T&&implements&BaseDao&T&{
protected&SessionFactory&sessionF
private&Class&T&&&
&*&构造方法
public&BaseDaoImpl()&{
//&同过反射得到T的真实类型
ParameterizedType&pt&=&(ParameterizedType)&this.getClass()
.getGenericSuperclass();
this.clazz&=&(Class)&pt.getActualTypeArguments()[0];
&*&日返回所有对象集合
&*&@return
public&List&T&&findAll()&{
return&(List&T&)&getSession().createQuery(
"FROM&"&+&clazz.getSimpleName()).list();
&*&根据hql放回所有符合条件的对象集合
&*&@param&hql 查询的hql语句
&*&@return
public&List&T&&findAll(String&hql,List&Object&&params){
Query&q&=&getSession().createQuery(hql);
for(int&i=0;i&params.size();i++){
q.setParameter(i,&params.get(i));
return&(List&T&)q.list();
&*&根据id数据返回对象集合
&*&@param&id
&*&@return
public&List&T&&findByIds(String[]&ids)&{
if&(ids&==&null&||&ids.length&==&0)&{
return&Collections.EMPTY_LIST;//&返回一个不可操作的空集合
return&(List&T&)&getSession().createQuery(
"FROM&"&+&clazz.getSimpleName()&+&"&WHERE&id&IN&(:ids)")
.setParameter("ids",&ids).list();
&*&根据分页信息返回所有的对象集合
&*&@param&page
&*&@param&pageSize
&*&@return
public&List&T&&findByPage(int&page,&int&pageSize)&{
return&(List&T&)&getSession().createQuery(
"FROM&"&+&clazz.getSimpleName()).setFirstResult(
(page&-&1)&*&pageSize).setMaxResults(pageSize).list();
&*&根据分页信息返回所有的对象集合
&*&@param&hql
&*&&&&&&&&&&&&传入的hql语句
&*&@param&page
&*&@param&pageSize
&*&@return
public&List&T&&findByPage(String&hql,List&Object&&params,&int&page,&int&pageSize)&{
Query&q&=&getSession().createQuery(hql);
for(int&i=0;i&params.size();i++){
q.setParameter(i,params.get(i));
return&(List&T&)&q.setFirstResult((page&-&1)&*&pageSize)
.setMaxResults(pageSize)
&*&根据id返回对象
&*&@param&id
&*&@return
public&T&findById(String&id)&{
return&(T)&getSession().get(clazz,&id);
&*&更具用户的属性返回对象
&*&@param&proName
&*&@param&proValue
&*&@return
public&List&T&&findByPropertiy(String&proName,String&proValue){
return&(List&T&)&getSession().createQuery(
"FROM&"&+&clazz.getSimpleName()&+&"&WHERE&"+proName+"&=&:value")
.setParameter("value",&proValue).list();
&*&计算记录数量
&*&@return
public&long&count(){
return&(Long)getSession()
.createQuery("FROM&"+clazz.getSimpleName())
.uniqueResult();
&*&根据hql语句,计算条件记录数量
&*&@return
public&long&count(String&hql,List&Object&&params){
Query&q&=&getSession().createQuery(hql);
for(int&i=0;i&params.size();i++){
q.setParameter(i,params.get(i));
return&(Long)&q.uniqueResult();
&*&根据id删除对象
&*&@param&id
public&void&delete(String&id)&{
getSession().delete(getSession().get(clazz,&id));
&*&根据id数组删除对象
&*&@param&ids
public&void&deleteByIds(String[]&ids)&{
for&(String&i&:&ids)&{
delete(i);
&*&更新数据库中的对象信息
&*&@param&entity
public&void&update(T&entity)&{
getSession().update(entity);
&*&向数据库中添加对象记录
&*&@param&entity
public&void&add(T&entity)&{
getSession().save(entity);
protected&Session&getSession()&{
System.out.println(sessionFactory);
return&sessionFactory.getCurrentSession();
hibernate配置文件sessionfactory添加&&property&name=&"hibernate.current_session_context_class"&thread&/property&试试
引用&2&楼&zyf814&的回复:hibernate配置文件sessionfactory添加&&property&name=&"hibernate.current_session_context_class"&thread&/property&试试
&!--&配置SessionFactory&--&
&bean&id="sessionFactory"&class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&
&property&name=&"hibernate.current_session_context_class"&value="thread"&/&
&property&name="dataSource"&ref="dataSource"&/&
&property&name="hibernateProperties"&
&prop&key="hibernate.dialect"&org.hibernate.dialect.MySQLDialect&/prop&
&prop&key="hibernate.hbm2ddl.auto"&update&/prop&
&prop&key="hibernate.show_sql"&true&/prop&
&prop&key="hibernate.format_sql"&true&/prop&
&/property&
&property&name="annotatedClasses"&
&value&com.jd.oa.entity.User&/value&
&/property&
报错了,说没有这个配置项!!
引用&3&楼&u&的回复:Quote: 引用&2&楼&zyf814&的回复:
hibernate配置文件sessionfactory添加&&property&name=&"hibernate.current_session_context_class"&thread&/property&试试
&!--&配置SessionFactory&--&
&bean&id="sessionFactory"&class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&
&property&name=&"hibernate.current_session_context_class"&value="thread"&/&
&property&name="dataSource"&ref="dataSource"&/&
&property&name="hibernateProperties"&
&prop&key="hibernate.dialect"&org.hibernate.dialect.MySQLDialect&/prop&
&prop&key="hibernate.hbm2ddl.auto"&update&/prop&
&prop&key="hibernate.show_sql"&true&/prop&
&prop&key="hibernate.format_sql"&true&/prop&
&/property&
&property&name="annotatedClasses"&
&value&com.jd.oa.entity.User&/value&
&/property&
报错了,说没有这个配置项!!
换成hibernate3试试&hibernate4估计设计不同了也可能
引用&3&楼&u&的回复:Quote: 引用&2&楼&zyf814&的回复:
hibernate配置文件sessionfactory添加&&property&name=&"hibernate.current_session_context_class"&thread&/property&试试
&!--&配置SessionFactory&--&
&bean&id="sessionFactory"&class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&
&property&name=&"hibernate.current_session_context_class"&value="thread"&/&
&property&name="dataSource"&ref="dataSource"&/&
&property&name="hibernateProperties"&
&prop&key="hibernate.dialect"&org.hibernate.dialect.MySQLDialect&/prop&
&prop&key="hibernate.hbm2ddl.auto"&update&/prop&
&prop&key="hibernate.show_sql"&true&/prop&
&prop&key="hibernate.format_sql"&true&/prop&
&/property&
&property&name="annotatedClasses"&
&value&com.jd.oa.entity.User&/value&
&/property&
报错了,说没有这个配置项!!
我刚刚试了可以&我是这样配置的&session-factory&
&property&name="hibernate.connection.url"&jdbc:mysql://127.0.0.1:3306/hibernate3.3.2?useUnicode=true&characterEncoding=UTF-8&/property&&&
&&&&&property&name="hibernate.connection.driver_class"&com.mysql.jdbc.Driver&/property&&&
&&&&&property&name="hibernate.connection.username"&root&/property&&&
&&&&&property&name="hibernate.connection.password"&sa&/property&&&
&&&&&property&name="hibernate.connection.isolation"&2&/property&
&property&name="show_sql"&true&/property&
&property&name="dialect"&org.hibernate.dialect.MySQLDialect&/property&&
&property&name=&"hibernate.current_session_context_class"&thread&/property&
&/session-factory&
你那里应该配置到hibernateProperties里面吧&这个属于hibernate属性
回复&nbsp>&nbsp
&nbsp>&nbsp
&nbsp>&nbsp
Hibernate整合进spring--使用hibernateTemplate.getSessionFactory().getCurrentSession()
摘要:1单独使用hibernate处理事物本来只用hibernate开发,从而可以省了DAO层实现数据库访问和跨数据库,也可以对代码进行更好的封装,当我们web中单独使用hibernate时,我们需要单独的处理hibernate的事务,我是使用filter来对事务进行控制的:单独使用hibernate使用filter进行事务控制:HibernateSessionFilter.javapublicclassHibernateSessionFilterimplementsFilter{
1 单独使用hibernate处理事物
本来只用hibernate开发,从而可以省了DAO层实现数据库访问和跨数据库,也可以对代码进行更好的封装,当我们web中单独使用hibernate时,我们需要单独的处理hibernate的事务,我是使用filter来对事务进行控制的:
单独使用hibernate使用filter进行事务控制:
HibernateSessionFilter.java
public class HibernateSessionFilter implements Filter { public void destroy() {
} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
Session session = HibernateUtils.openSession();
Transaction tx =
tx = session.beginTransaction();
chain.doFilter(request, response);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
throw new RuntimeException(e);
} finally {
HibernateUtils.closeAndRemoveSession();
} } public void init(FilterConfig arg0) throws ServletException { }}
&filter-name&hibernateSessionFilter&/filter-name&
&filter-class& syx.jpkc.filter.HibernateSessionFilter&/filter-class&
&filter-mapping&
&filter-name&hibernateSessionFilter&/filter-name&
&url-pattern&*.syx&/url-pattern&
&url-pattern&*.jsp&/url-pattern&
&url-pattern&*.eve&/url-pattern&
&/filter-mapping&
我主要在servlet(*.syx,*.eve)和jsp页面(没用struts)需要和数据库操作,所以需要使用事务处理。
上面我们还用到了一个 HibernateUtils的小工具类,主要为了获取Session对象和一点优化:
HibernateUitls.java
public class HibernateUtils { private static Map&Thread, Session& sessionM private static SessionFactory sessionF static {
sessionMap = new HashMap&Thread, Session&();
sessionFactory = new Configuration().configure().buildSessionFactory(); } /**
* can only use in web filter, beause it should remove and clear resources
*/ public static Session openSession() {
System.out.println(Thread.currentThread().getStackTrace()[1] + & run in & + new Date());
Session session = sessionMap.get(Thread.currentThread());
if (session == null) {
session = sessionFactory.openSession();
sessionMap.put(Thread.currentThread(), session);
} public static Session getCurrentSession() {
return sessionMap.get(Thread.currentThread()); } public static void closeAndRemoveSession() {
System.out.println(Thread.currentThread().getStackTrace()[1]+ & run in & + new Date());//
Session session = sessionMap.remove(Thread.currentThread());
if (session != null) {
session.close();
2 hibernate整合进spring后的事物处理
spring事物处理的方式有很多,详见:
介绍常用的:
spring annotation声明式的事务管理
1) 事物处理层?
比如保存一个User,可以在Service层和DAOImpl层实现:
public void save(User u) { userDAO.save(u);}public void save(User u) { System.out.println(&save user from:& + this); Session s = sessionFactory.openSession(); s.beginTransaction(); s.save(u); s.getTransaction().commit(); s.close();}
假如我们还有个日志记录,没保存一个User对象,要写入日志进入数据库。
而save(log) 和 save(user)必须处在同一事务中,所以不能放在DAOImpl层,事务处理在Service层。
2) 一般的事务处理
Session sess = factory.openSession(); T try {
tx = sess.beginTransaction();
//do some work
//save(user);
//save(log);
tx.commit(); } catch (Exception e) {
if (tx!=null) tx.rollback(); } finally {
sess.close(); }
并且要在实现层中的save()方法中也要加入事务处理,如果出出现异常要throws给上级处理!
并且实现层中的session必须使用openCurrentSession()得到。
Session s = sessionFactory.getCurrentSession();
s.save(u);
3) spring annotation事务处理
Beans.xml中引入相应的xml命名空间和相应配置:
xmlns:tx=&http://www.springframework.org/schema/tx& http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd &tx:annotation-driven transaction-manager=&txManager&/& &bean id=&txManager& class=&org.springframework.orm.hibernate3.HibernateTransactionManager&&
&property name=&sessionFactory& ref=&sessionFactory& /& &/bean& &bean id=&dataSource&
class=&org.apache.commons.dbcp.BasicDataSource&
destroy-method=&close&&
&property name=&driverClassName&
value=&${jdbc.driverClassName}& /&
&property name=&url& value=&${jdbc.url}& /&
&property name=&username& value=&${jdbc.username}& /&
&property name=&password& value=&${jdbc.password}& /& &/bean& &bean id=&sessionFactory&
class=&org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean&&
&property name=&dataSource& ref=&dataSource& /&
&property name=&annotatedClasses&&
&value&com.syx.model.User&/value&
&value&com.syx.model.Log&/value&
&/property&
&property name=&hibernateProperties&&
&prop key=&hibernate.dialect&&org.hibernate.dialect.MySQLDialect&/prop&
&prop key=&hibernate.show_sql&&true&/prop&
&prop key=&current_session_context_class&&thread&/prop&
&/property& &/bean& Save方法: public void save(User u) {
Session s = sessionFactory.getCurrentSession();
s.save(u); } public void save(Log log) {
Session s = sessionFactory.getCurrentSession();
s.save(log); } Service层处理: @Component(&userService&) public class UserService {
UserDAO userDAO =
LogDAO logDAO =
public LogDAO getLogDAO() {
return logDAO;
@Resource(name=&logDAOMySQLImpl&)
public void setLogDAO(LogDAO logDAO) {
this.logDAO = logDAO;
@Transactional
public void save(User u) {
userDAO.save(u);
Log log = new Log();
log.setMsg(u.getName() + & saved in & + new Date());
logDAO.save(log);
public UserDAO getUserDAO() {
return userDAO;
@Resource(name=&userDAOMySQLImpl&)
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
4) @Transactional详解
什么时候rollback
运行期异常,非运行期异常不会触发rollback
必须uncheck (没有catch)
不管什么异常,只要你catch了,spring就会放弃管理
事务传播特性:propagation_required
默认是 REQUIRED ,意思是有我们就用现成的,没的我们就创造一个,其他详细见文档
spring xml声明式的事务管理
配置环境和annotation版本一致,只是在用@Transactional处注释调用,在beans.xml中加入如下配置:
&!-- spring tranception xml config --& &aop:config&
&aop:pointcut id=&serviceOperation&
expression=&execution(* com.syx.service..*.*(..))& /&
&aop:advisor pointcut-ref=&serviceOperation& advice-ref=&txAdvice& /& &/aop:config& &tx:advice id=&txAdvice&
transaction-manager=&txManager&&
&tx:attributes&
&tx:method name=&getUser& read-only=&true& /&
&tx:method name=&save& /&&!-- 相当于在上面切面效果 --&
&/tx:attributes& &/tx:advice&
3 hibernateTemplate.getSessionFactory().getCurrentSession()
我们使用spring和hibernate结合,操作数据库最常用可能是HibernateTemplate,HibernateTemplate中集成了很多使用的方法,可惜的是没的createQuery方法,也许我们使用hibernate的时候喜欢使用Query,我们可能会封装hibernateTemplate.getSessionFactory().getCurrentSession()方法得到Session,session创建Query,这是一个方法,但你应该会得到异常 “createQuery without an active transaction”,因为使用hibernateTemplate.getSessionFactory().getCurrentSession(),你是使用的hibernate的事务管理,而你指望spring管理的事物是hibernateTemplate,所以你会提示没有打开事务的异常,解决方法:1)使用hibernate事务处理,就像上面单独使用hibernate一样,但这也许不是你想要的。2)使用hibernateTemplate的HibernateCallBack回调:
return hibernateTemplate.executeWithNativeSession( new HibernateCallback&List&T&&() { public
List&T& doInHibernate(Session session)
throws HibernateException, SQLException {
return session.createQuery
(&FROM & + entityClass.getName() + & WHERE id IN (:ids)&)//
.setParameterList(&ids&, idList).list(); }
实际上hibernateTemplate中封装的find方法也很强大,如果熟练使用完全可以替代createQuery的。
如果出现异常:对同一个集合处理不能使用2个session,这是因为getCurrentSession方法出错,导致打开一个新的session,检查配置文件,如果使用tomcat+spring+hibernate 配置hibernate.current_session_context_class 最好为thread,虽然支持jta,配置比较麻烦,而且jta支持多个sessionFactory,即可以跨数据库,比较强大!
如果hibernate+spring出现session没有提交情况,应该是你让spring负责事务处理,而你有使用了hibernate的session,从而脱离spring事务处理,即没的begintransaction和commit之类的操作了。
以上是的内容,更多
的内容,请您使用右上方搜索功能获取相关信息。
若你要投稿、删除文章请联系邮箱:zixun-group@service.aliyun.com,工作人员会在五个工作日内给你回复。
云服务器 ECS
可弹性伸缩、安全稳定、简单易用
&40.8元/月起
预测未发生的攻击
&24元/月起
为您提供0门槛上云实践机会
你可能还喜欢
你可能感兴趣
阿里云教程中心为您免费提供
Hibernate整合进spring--使用hibernateTemplate.getSessionFactory().getCurrentSession()相关信息,包括
的信息,所有Hibernate整合进spring--使用hibernateTemplate.getSessionFactory().getCurrentSession()相关内容均不代表阿里云的意见!投稿删除文章请联系邮箱:zixun-group@service.aliyun.com,工作人员会在五个工作日内答复
售前咨询热线
支持与服务
资源和社区
关注阿里云
InternationalHibernateSessionFactory.getSessionFactory().getCurrentSession(); 获取到的session不是同一个勒?_百度知道
HibernateSessionFactory.getSessionFactory().getCurrentSession(); 获取到的session不是同一个勒?
Session session=HibernateSessionFactory.getSessionFactory().getCurrentSession();
Session session2=HibernateSessionFactory.getSessionFactory().getCurrentSession();
这2个session不一样啊,
public class HibernateSessionFactory {
public s...
上面的没有说清楚, 是这样的:public void addUser(User user) {
Session session=HibernateSessionFactory.getSessionFactory().getCurrentSession();
Transaction t=session.beginTransaction();
Session session2=HibernateSessionFactory.getSessionFactory().getCurrentSession();
System.out.println(session==session2);
......} 为什么session不一样勒?
我有更好的答案
Configuration cf=new Configuration().configure();你每次请求都会创建一个新的Configuration对象得到的 能一样吗?
采纳率:35%
为您推荐:
其他类似问题
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。getCurrentSession得到session对象配置
JUit报错:org.hibernate.HibernateException: No CurrentSessionContext configured!hibernate.cfg.xml配置文件已经配置了:&property name="hibernate.current_session_context_class"&thread&/property&测试文件:package Simport org.hibernate.Simport org.hibernate.SessionFimport org.hibernate.cfg.Cimport org.hibernate.service.ServiceRimport org.hibernate.service.ServiceRegistryBimport org.junit.Aimport org.junit.Tpublic class SessionTest { @Test public void testopenSession() {
//1.创建配置对象
Configuration config=new Configuration().configure();
//2.创建服务配置对象
ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().
applySettings(config.getProperties()).buildServiceRegistry();
//3.创建会话工厂
SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);
//4.打开会话
Session session=sessionFactory.openSession();
if(session!=null)
System.out.print("session创建成功");
System.out.print("session创建失败");
@Test public void testgetCurrentSession() {
//1.创建配置对象
Configuration config=new Configuration().configure();
//2.创建服务配置对象
ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().
applySettings(config.getProperties()).buildServiceRegistry();
//3.创建会话工厂
SessionFactory sessionFactory=config.buildSessionFactory(serviceRegistry);
//4.获得会话
Session session2 =sessionFactory.getCurrentSession();
if(session2!=null)
System.out.print("session创建成功");
System.out.print("session创建失败");
} }} 求大神指点这里是哪里错误
你的hibernate版本是什么,有时候是因为hibernate4/5中修改了创建sessionFactory的方式而引起的
你还没有登录,请先登录或注册慕课网帐号
要用getCurrentSession();需要在hibernate.cfg.xml 配hibernate.current_session_context_class =thread
你还没有登录,请先登录或注册慕课网帐号
76618人关注
Copyright (C) 2018 imooc.com All Rights Reserved | 京ICP备 号-11

我要回帖

更多关于 hibernate get load 的文章

 

随机推荐