我是初学者,正如我所理解的,@Transactional只需确保用@Transactional注释的类或方法的所有内部工作都封装在一个事务中,来自外部源的所有调用都会创建一个新事务,但是为什么我们实际上需要在下面的存储库中使用这些注释,以及在常见情况下将其与readOnly = true一起使用有什么好处呢?这是使用 Spring & Hibernate (https://github.com/spring-projects/spring-petclinic)的Spring宠物诊所示例应用程序。
/**
* 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 the data store.
* @return a Collection of {@link PetType}s.
*/
@Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name")
@Transactional(readOnly = true)
List<PetType> findPetTypes();
/**
* Retrieve a {@link Pet} from the data store by id.
* @param id the id to search for
* @return the {@link Pet} if found
*/
@Transactional(readOnly = true)
Pet findById(Integer id);
/**
* Save a {@link Pet} to the data store, either inserting or updating it.
* @param pet the {@link Pet} to save
*/
void save(Pet pet);
}https://stackoverflow.com/questions/44984781
复制相似问题