使用 Spring 自动进行 Hibernate 事务管理?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/758050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Automatic Hibernate Transaction Management with Spring?
提问by James McMahon
How far does the spring framework go with transaction handling? My reading of the book "Spring In Action" suggestions with its examples that you create DAO methods that don't worry about Session and Transaction management fairly simply by setting up a session factory and transaction template in XML and then wiring them into your DAO. SpringSource.org's documentation, on the other hand, suggests that need tons of XML and/or annotation to make this happen.
spring 框架在事务处理方面走多远?我对“Spring In Action”一书的阅读建议及其示例,您可以通过在 XML 中设置会话工厂和事务模板,然后将它们连接到您的 DAO 来创建 DAO 方法,这些方法无需担心会话和事务管理。另一方面,SpringSource.org 的文档表明需要大量的 XML 和/或注释来实现这一点。
What is the truth here, what is the simplest way I can take code along the lines of
这里的真相是什么,我可以按照以下方式编写代码的最简单方法是什么?
get session from sessionfactory
open transaction
preform database actions
commit transaction with error handling
and make it just
让它只是
preform database actions
reducing the amount of boiler plate transactional code that I have across my methods to a minimum?
将我在我的方法中拥有的样板事务代码的数量减少到最低限度?
采纳答案by skaffman
Spring provides at least 3 ways of transaction demarcation:
Spring 提供了至少 3 种事务划分方式:
1) Programmatic handling, via TransactionTemplate or PlatformTransactionManager - light on config, but invasive
1) 编程处理,通过 TransactionTemplate 或 PlatformTransactionManager - 配置简单,但具有侵入性
2) Declarative via XML - verbose XML, but non-invasive
2) 通过 XML 声明 - 冗长的 XML,但非侵入性
3) Declarative via annotations - light on XML, not invasive
3) 通过注解声明性 - 轻量 XML,非侵入性
Which one you pick depends on which one best suits your needs, Spring doesn't make that choice for you. From your question, it sounds like the annotation approach is what you're after.
您选择哪一个取决于哪一个最适合您的需求,Spring 不会为您做出那个选择。从您的问题来看,这听起来像是您所追求的注释方法。
I suggest reading the Spring reference manual, the section of annotation-driven transaction handling. It's clear and concise.
我建议阅读 Spring 参考手册,注解驱动的事务处理部分。它清晰简洁。
I always consult the ref docs first, and only consult a book if it's not in the docs.
我总是先查阅参考文档,只有在文档中没有的时候才查阅一本书。
回答by topchef
There is some work you are supposed to do to be able to do just that but it's not much at all. Supposedly, you will use JPA with pick your own provider, e.g. Hibernate. Then you need to place persistence.xml that defines the persistence unit in the META-INF folder:
有一些你应该做的工作才能做到这一点,但它并不多。据说,您将使用 JPA 并选择您自己的提供程序,例如 Hibernate。然后你需要将定义持久化单元的 persistence.xml 放在 META-INF 文件夹中:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="YourDatabasePersistenceUnitName" transaction-type="RESOURCE_LOCAL"/>
</persistence>
Next, define everything necessary for database connection in the Spring application context you use, at minimum it should contain these:
接下来,在您使用的 Spring 应用程序上下文中定义数据库连接所需的一切,至少应包含以下内容:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" scope="singleton">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="YourDatabasePersistenceUnitName"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="POSTGRESQL" />
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="showSql" value="true"/>
<property name="generateDdl" value="false"/>
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
Some properties above may be changed or added depending on your needs. The example is for JPA with Hibernate and PostgreSQL database as you may have guessed.
上面的某些属性可能会根据您的需要进行更改或添加。该示例适用于您可能已经猜到的带有 Hibernate 和 PostgreSQL 数据库的 JPA。
Now you can simply define your data access methods like this:
现在您可以简单地定义您的数据访问方法,如下所示:
@Repository
@Transactional
public class UserJpaDAO {
protected EntityManager entityManager;
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
public void save(User theUser) {
entityManager.persist(theUser);
}
public User update(User theUser) {
return entityManager.merge(theUser);
}
}
where User is a JPA entity defined by your application. You may manager transactions at manager/controller layer that calls your DAOs - in fact I do it that way - but I placed it together here not to clutter example too much.
其中 User 是您的应用程序定义的 JPA 实体。您可以在管理器/控制器层管理调用您的 DAO 的事务 - 事实上我是这样做的 - 但我把它放在一起不是为了让示例过于混乱。
Nice references that you may want to go straight to instead of my examples is http://icoloma.blogspot.com/2006/11/jpa-and-spring-fworing-cooltm_26.htmlThe top 3 links it references are worth going to as well.
您可能想要直接访问而不是我的示例的不错参考文献是 http://icoloma.blogspot.com/2006/11/jpa-and-spring-fworing-cooltm_26.html它引用的前 3 个链接值得一看以及。

