春天 + Hibernate:事务提交但数据未持久化

发布于 2024-12-21 02:59:26 字数 6586 浏览 2 评论 0原文

我正在使用以下实现 Hibernate 持久性的服务层类:

public class AccountsManagerImpl implements IAccountsManager {
    private static Logger log = LoggerFactory.getLogger(AccountsManagerImpl.class);

    private final SessionFactory sessionFactory;
    private AccountDao accountDao;

    public AccountsManagerImpl(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
        accountDao = new AccountDao(sessionFactory);
    }

    @Override
    public void createAccount(final Account account) {
        runInTransaction(new Runnable() {
            public void run() {
                accountDao.add(account);
            }
        });
    }

    @Override
    public void modifyAccount(final Account account) {
        runInTransaction(new Runnable() {
            public void run() {
                accountDao.update(account);
            }
        });
    }

    @Override
    public void deleteAccount(final Account account) {
        runInTransaction(new Runnable() {
            public void run() {
                accountDao.remove(account);
            }
        });
    }

    private void runInTransaction(Runnable runnable) {
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            runnable.run();
            tx.commit();
        }
        catch(Exception e) {
            log.error("Exception during transaction, rolling back", e);
            if(tx != null && tx.isActive()) {
                try {
                    tx.rollback();
                }
                catch(Exception e2) {
                    log.error("Failed to rollback transaction", e2);
                }
                throw new IllegalStateException("Transaction failed", e);
            }
        }
    }

}

该类与实体类一起位于一个单独的库 (.jar) 中,该库插入到 web 应用程序中。 Webapp 使用此类进行以下 Spring 配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    ">

    <!-- Scans within the base package of the application for @Components to configure as beans -->
    <bean id="placeholderConfig"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:db.properties"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="schemaUpdate" value="true"/>
        <property name="packagesToScan">
            <list>
                <value>com.rcslabs.webcall.server.model</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.autocommit">false</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.format_sql">false</prop>
                <prop key="hibernate.dialect">${db.dialect}</prop>

                <prop key="hibernate.cache.use_query_cache">false</prop>
            </props>
        </property>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
    </bean>

    <bean
            class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

        <bean class="com.rcslabs.webcall.server.impl.AccountsManagerImpl">
        <constructor-arg ref="sessionFactory"/>
    </bean>

</beans>

当调用 createAccount 方法时,提交事务,对象从数据库序列中获取其 id,但数据未持久化(无 INSERT,表为空):

2011-12-12 14:45:22,932 DEBUG: org.hibernate.transaction.JDBCTransaction - begin
2011-12-12 14:45:22,932 DEBUG: org.hibernate.jdbc.ConnectionManager - opening JDBC connection
2011-12-12 14:45:22,932 DEBUG: org.hibernate.transaction.JDBCTransaction - current autocommit status: true
2011-12-12 14:45:22,932 DEBUG: org.hibernate.transaction.JDBCTransaction - disabling autocommit
2011-12-12 14:45:22,934 DEBUG: org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
2011-12-12 14:45:22,936 DEBUG: org.hibernate.SQL - select nextval ('hibernate_sequence')
2011-12-12 14:45:22,940 DEBUG: org.hibernate.id.SequenceGenerator - Sequence identifier generated: BasicHolder[java.lang.Long[12]]
2011-12-12 14:45:22,940 DEBUG: org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
2011-12-12 14:45:22,940 DEBUG: org.hibernate.event.def.AbstractSaveEventListener - generated identifier: 12, using strategy: org.hibernate.id.SequenceGenerator
2011-12-12 14:45:22,946 DEBUG: org.hibernate.transaction.JDBCTransaction - commit
2011-12-12 14:45:22,947 DEBUG: org.hibernate.transaction.JDBCTransaction - re-enabling autocommit
2011-12-12 14:45:22,947 DEBUG: org.hibernate.transaction.JDBCTransaction - committed JDBC Connection
2011-12-12 14:45:22,947 DEBUG: org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!

出了什么问题?如何正确持久化数据?

编辑:

我不想在库中使用 Spring 声明式事务 (@Transactional) 并依赖于相关的 Spring 类。我只想将正确的 SessionFactory 传递给 Manager 并让它工作。

I'm using the following service-layer class that implements Hibernate persistence:

public class AccountsManagerImpl implements IAccountsManager {
    private static Logger log = LoggerFactory.getLogger(AccountsManagerImpl.class);

    private final SessionFactory sessionFactory;
    private AccountDao accountDao;

    public AccountsManagerImpl(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
        accountDao = new AccountDao(sessionFactory);
    }

    @Override
    public void createAccount(final Account account) {
        runInTransaction(new Runnable() {
            public void run() {
                accountDao.add(account);
            }
        });
    }

    @Override
    public void modifyAccount(final Account account) {
        runInTransaction(new Runnable() {
            public void run() {
                accountDao.update(account);
            }
        });
    }

    @Override
    public void deleteAccount(final Account account) {
        runInTransaction(new Runnable() {
            public void run() {
                accountDao.remove(account);
            }
        });
    }

    private void runInTransaction(Runnable runnable) {
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            runnable.run();
            tx.commit();
        }
        catch(Exception e) {
            log.error("Exception during transaction, rolling back", e);
            if(tx != null && tx.isActive()) {
                try {
                    tx.rollback();
                }
                catch(Exception e2) {
                    log.error("Failed to rollback transaction", e2);
                }
                throw new IllegalStateException("Transaction failed", e);
            }
        }
    }

}

This class, along with entity classes, is in a separate library (.jar), that is plugged into a webapp. Webapp uses this class with the following Spring configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    ">

    <!-- Scans within the base package of the application for @Components to configure as beans -->
    <bean id="placeholderConfig"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:db.properties"/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="schemaUpdate" value="true"/>
        <property name="packagesToScan">
            <list>
                <value>com.rcslabs.webcall.server.model</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.autocommit">false</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.format_sql">false</prop>
                <prop key="hibernate.dialect">${db.dialect}</prop>

                <prop key="hibernate.cache.use_query_cache">false</prop>
            </props>
        </property>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.username}"/>
        <property name="password" value="${db.password}"/>
    </bean>

    <bean
            class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

        <bean class="com.rcslabs.webcall.server.impl.AccountsManagerImpl">
        <constructor-arg ref="sessionFactory"/>
    </bean>

</beans>

When the createAccount method is called, transaction is commited, the object gets it's id from the database sequence, but the data is not persisted (no INSERT, the table is empty):

2011-12-12 14:45:22,932 DEBUG: org.hibernate.transaction.JDBCTransaction - begin
2011-12-12 14:45:22,932 DEBUG: org.hibernate.jdbc.ConnectionManager - opening JDBC connection
2011-12-12 14:45:22,932 DEBUG: org.hibernate.transaction.JDBCTransaction - current autocommit status: true
2011-12-12 14:45:22,932 DEBUG: org.hibernate.transaction.JDBCTransaction - disabling autocommit
2011-12-12 14:45:22,934 DEBUG: org.hibernate.jdbc.AbstractBatcher - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
2011-12-12 14:45:22,936 DEBUG: org.hibernate.SQL - select nextval ('hibernate_sequence')
2011-12-12 14:45:22,940 DEBUG: org.hibernate.id.SequenceGenerator - Sequence identifier generated: BasicHolder[java.lang.Long[12]]
2011-12-12 14:45:22,940 DEBUG: org.hibernate.jdbc.AbstractBatcher - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
2011-12-12 14:45:22,940 DEBUG: org.hibernate.event.def.AbstractSaveEventListener - generated identifier: 12, using strategy: org.hibernate.id.SequenceGenerator
2011-12-12 14:45:22,946 DEBUG: org.hibernate.transaction.JDBCTransaction - commit
2011-12-12 14:45:22,947 DEBUG: org.hibernate.transaction.JDBCTransaction - re-enabling autocommit
2011-12-12 14:45:22,947 DEBUG: org.hibernate.transaction.JDBCTransaction - committed JDBC Connection
2011-12-12 14:45:22,947 DEBUG: org.hibernate.jdbc.ConnectionManager - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!

What is wrong? How to persist data correctly?

Edit:

I wouldn't like to use Spring declarative transactions (@Transactional) in the library and depend on related Spring classes. I just want to pass the right SessionFactory to the Manager and have it working.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

迷你仙 2024-12-28 02:59:26

为什么不使用:

<tx:annotation-driven transaction-manager="transactionManager" />

然后

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
    p:entityManagerFactory-ref="entityManagerFactory" 
    p:dataSource-ref="dataSource" />  

您可以简单地在您想要包装在事务中的任何方法之上使用 @Transactional 注释?

IE

    @Override  
@Transactional
public void createAccount(final Account account) {
     accountDao.add(account); 
}

Why not use:

<tx:annotation-driven transaction-manager="transactionManager" />

and

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
    p:entityManagerFactory-ref="entityManagerFactory" 
    p:dataSource-ref="dataSource" />  

then you can simply use the the @Transactional annotation above whatever method you want wrapped in a transaction?

i.e

    @Override  
@Transactional
public void createAccount(final Account account) {
     accountDao.add(account); 
}
怀中猫帐中妖 2024-12-28 02:59:26

查看了org.springframework.orm.hibernate3.HibernateTransactionManager的代码。

在 tx.commit() 之前添加 session.flush() 解决了问题。

Looked through the code of org.springframework.orm.hibernate3.HibernateTransactionManager.

Adding session.flush() before tx.commit() solved the problem.

冷了相思 2024-12-28 02:59:26

我在您的应用程序中没有发现问题,但我可以回答第二个问题:“如何正确保存数据?”

使用 Spring Transaction Template,而不是一些自己的实现。

I dont find the problem in you app, but I can answer the second question: "How to persist data correctly?"

Use Spring Transaction Template, instead of some own implementation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文