一、问题 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>