我对 Spring 和 Hibernate 事务很困惑。我有以下示例代码。
我想知道是否
getCurrentSession().beginTransaction()也应该使用,是否应该与它结合使用@Transactional?配置
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:2000/HiberProject" />
<property name="username" value="jack" />
<property name="password" value="jack" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
depends-on="dataSource">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.hiberproject.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
Run Code Online (Sandbox Code Playgroud)
服务
@Service
public class SampleRecordsServiceImpl implements SampleRecordsService{
@Autowired
SampleRecordsRepository sampleRecordsRepository;
@Override
@Transactional(readOnly=true)
public Record retrieveRecord(long id){
return sampleRecordsRepository.retrieveRecord(id);
}
}
Run Code Online (Sandbox Code Playgroud)
存储库
@Repository
public class SampleRecordsRepository implements SampleRecordsRepository{
@Autowired
SessionFactory sessioFactory;
@Override
public Record retrieveRecord(long id){
return (Record) sessionFactory.getCurrentSession().get(Record.class,id);
}
}
Run Code Online (Sandbox Code Playgroud)
是的,@Transactional当您使用 Spring 来管理事务时,只使用这样的注释就可以了。
不,你不需要这样做!如果您@Transactional在服务中使用注释,那么 Spring 会负责您的持久层来管理事务。您所需要的只是在 Spring 配置中声明持久层特定的事务管理器。因此,您不需要通过session.beginTransaction()与 一起使用来管理 hibernate 会话的事务@Transactional。
有关更多信息,请参阅使用文档@Transactional。
| 归档时间: |
|
| 查看次数: |
2188 次 |
| 最近记录: |