SSH下,处理问题No Session,createCriteria,Could not open connection

本文针对SSH框架在实际应用过程中遇到的三个典型错误进行了解析并提供了相应的解决方案,包括NoSessionfoundforcurrentthread、createCriteriaisnotvalidwithoutactivetransaction及Couldnotopenconnection等问题。

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

一、问题 org.hibernate.HibernateException: No Session found for current thread

本人是通过myeclipse下创建的ssh框架,然而在添加hibernate时,在运行

  Session session=sessionFactory.getCurrentSession();

报错:org.hibernate.HibernateException: No Session found for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)

解决方法

在spring配置文件的hibernateProperties属性下添加hibernate.current_session_context_class属性,将线程配置成Thread级别的。

<property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop        key="hibernate.current_session_context_class">
                thread
                </prop>
            </props>
        </property>

currentSession与当前线程绑定,在事务结束后自动关闭。

二、createCriteria is not valid without active transaction

Dao层在执行 Criteria c =session.createCriteria(Admin.class); 报错:
org.hibernate.HibernateException: createCriteria is not valid without active transaction
org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)

解决方法

在使用criteria时,执行步骤应如下:

 Session session=sessionFactory.getCurrentSession();
           Transaction tx =session.beginTransaction();
            //创建criteria对象
               Criteria c =session.createCriteria(Admin.class);
               //使用Example 工具类创建示例对象example作为查询条件
               Example example=Example.create(condition);
               c.add(example);
               list=c.list();
               tx.commit();

三、Could not open connection

SSH框架下查询数据库时,遇到了一个错误:org.hibernate.exception.GenericJDBCException: Could not open connection
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)

解决方法

myeclipse中在自动配置spring配置文件时,可能不会自动添加用于连接数据库的JDBC驱动的property标记,这时就需要自己手动填写

<bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource">
        <!-- 指定连接数据库的JDBC驱动-->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/test"></property>
        <property name="username" value="root"></property>
        <property name="password" value=""></property>
</bean> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值