在我使用Hibernate的过程中一直遇到一些Exception,有些Exception遇到过多次,所以打算把这些异常记录下来;
1. Hibernate不能够获取当前的Session,获取时抛出异常如下
Exception in thread "main" org.hibernate.HibernateException: No session currently bound to execution context at org.hibernate.context.ManagedSessionContext.currentSession(ManagedSessionContext.java:74) at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:700) at com.tibco.hibernate.coreAPI.ExceptionTest.main(ExceptionTest.java:11)
部分Hibernate.cfg.xml配置如下
<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping class="com.tibco.hibernate.coreAPI.Student"/>
等效代码:
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = sessionFactory.getCurrentSession();
当我运行上面两行代码是就抛出上述异常;
解决办法:修给配置文件
<property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>
替换成
<property name="current_session_context_class">thread</property>
原因是Hibernate版本更新造成,Hibernate3.2之前current_session_context_class 为org.hibernate.context.ManagedSessionContext, 而之后为thread,修改后就不会抛出异常
2. org.hibernate.exception.SQLGrammarException,
异常如下:
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [com.xxx.hibernate.many2one.uni.xml.Group] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2329) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2836) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
原因com.xxx.hibernate.many2one.uni.xml.Group中group与Mysql中关键字冲突,
解决办法,把表名重新命名就可以
<class name="com.xxx.hibernate.many2one.uni.xml.Group" dynamic-update="true" table="t_group">