4

Javaコマンドラインアプリを使用してHibernate4.1.9をテストしています。現在のセッションコンテキストをスレッドに設定しました:

<property name="hibernate.current_session_context_class">thread</property>

しかし、呼び出すsessionFactory.getCurrentSession()と例外がスローされます。

Exception in thread "main" org.hibernate.HibernateException: get is not valid without active transaction
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
    at com.sun.proxy.$Proxy9.get(Unknown Source)
....

私は使用できますがopenSession、それは実際には問題ではありません(結局のところテストです)。getCurrentSessionメソッドを宣伝どおりに機能させることができない理由が気になります。

ありがとう。

4

2 に答える 2

3

sessionFactory.getCurrentSession()を最初に呼び出すと、新しいセッションが返されます。問題は私の設定にありました。

私はそれをこのように持っていました:

<property name="hibernate.current_session_context_class">thread</property>

これに変更した後、それは機能しました:

<property name="current_session_context_class">thread</property>
于 2013-03-02T00:56:48.363 に答える
0

少し古い質問ですが、正しく答えることを考えました。

プロパティ名hibernate.current_session_context_classをに変更することにより、current_session_context_classデフォルトを強制しますJTASessionContext

以下のスニペットは休止状態からのものSessionFactoryImplです。ところで、Environment.CURRENT_SESSION_CONTEXT_CLASSです"hibernate.current_session_context_class"ThreadLocalSessionContextこの問題が発生します。

private CurrentSessionContext buildCurrentSessionContext() {
        String impl = (String) properties.get( Environment.CURRENT_SESSION_CONTEXT_CLASS );
        // for backward-compatibility
        if ( impl == null ) {
            if ( canAccessTransactionManager() ) {
                impl = "jta";
            }
            else {
                return null;
            }
        }

        if ( "jta".equals( impl ) ) {
//          if ( ! transactionFactory().compatibleWithJtaSynchronization() ) {
//              LOG.autoFlushWillNotWork();
//          }
            return new JTASessionContext( this );
        }
        else if ( "thread".equals( impl ) ) {
            return new ThreadLocalSessionContext( this );
        }
        else if ( "managed".equals( impl ) ) {
            return new ManagedSessionContext( this );
        }
        else {
            try {
                Class implClass = serviceRegistry.getService( ClassLoaderService.class ).classForName( impl );
                return (CurrentSessionContext)
                        implClass.getConstructor( new Class[] { SessionFactoryImplementor.class } )
                        .newInstance( this );
            }
            catch( Throwable t ) {
                LOG.unableToConstructCurrentSessionContext( impl, t );
                return null;
            }
        }
    }

チェックしてくださいThreadLocalSessionContext.TransactionProtectionWrapper.invoke

于 2017-09-12T18:46:57.480 に答える