为什么我在Hibernate中需要Transaction才能进行只读操作?
以下事务是否锁定了数据库?
从DB获取的示例代码:
Transaction tx = HibernateUtil.getCurrentSession().beginTransaction(); // why begin transaction?
//readonly operation here
tx.commit() // why tx.commit? I don't want to write anything
Run Code Online (Sandbox Code Playgroud)
我可以用session.close() 而不是tx.commit()吗?
我正在使用只读数据库来获取我的项目中的一些数据.我们使用Spring v3和jpa以及hibernate
以下注释是否会使对我的存储库的所有调用都成为只读事务?或者我是否需要调用存储库的服务层上的注释
package com.blah.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
@Transactional(readOnly = true)
public interface ServiceToServerRepository extends JpaRepository<ServiceToServerJPA, String> {
}
Run Code Online (Sandbox Code Playgroud)
所以我们得到了所有的findOne,findAll是免费的.但任何更新都应该失败,因为它是一个只读事务
我尝试查看几个SO问题和spring文档,但仍然无法理解@Transactional(read-only = true).
它只能用于只读事务还是可以用于像下面这样实际读写数据库的事情
@Transactional(readOnly = true, propagation = Propagation.REQUIRED
, rollbackFor= {Exception.class})
public void doMultipleOperation(MyObj obj) throws Exception{
//call delete DAO method
//call insert DAO method
//call select DAO method
}
Run Code Online (Sandbox Code Playgroud)
我在 SO 上发现了类似的问题和其他多个问题,但我正在寻找更通俗易懂的答案。
我是新手,据我所知,@Transactional只需确保@Transactional将带有注释的类或方法的所有内部工作都包装在一个事务中,并且来自外部源的所有调用将创建一个新事务,但是为什么我们实际上需要这些注释?下面的存储库以及readOnly = true在常见情况下使用它的优势是什么?这是使用Spring&Hibernate(https://github.com/spring-projects/spring-petclinic)的Spring pet-clinic示例应用程序。
/**
* Repository class for <code>Pet</code> domain objects All method names are compliant with Spring Data naming
* conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
*
* @author Ken Krebs
* @author Juergen Hoeller
* @author Sam Brannen
* @author Michael Isvy
*/
public interface PetRepository extends Repository<Pet, Integer> {
/**
* Retrieve all {@link PetType}s from …Run Code Online (Sandbox Code Playgroud) spring hibernate transactions spring-transactions spring-data