为什么不用@Transactional我也能保存? [重复]

问题描述 投票:0回答:1

简化示例:

@Entity
public class Foo {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;
  private String bar;

  // getters + setters

}

public interface FooRepository extends CrudRepository<Foo, Integer> {
}

@Service
public class FooService {

  private final FooRepository repository;

  public FooService(FooRepository repository) {
    this.repository = repository;
  }

  public Foo save(Foo foo) {
    return repository.save(foo);
  }

}

从控制器调用

fooService.save(myNewFoo)
是可行的,虽然我预计它会失败(如果我正确理解事务),因为没有任何方法用
@Transactional
注释(而且我实际上希望它失败)。知道为什么会有这种行为吗?谁在幕后创建交易,如何避免这种情况?

其他详细信息:

  • Java 9
  • MySQL 连接器 6.0.6
  • 休眠 5.2.12
  • Spring Boot 2.0.0.M7
  • Spring Data JPA 2.0.2.RELEASE
java mysql hibernate spring-boot spring-data-jpa
1个回答
16
投票

Spring提供的

CrudRepository#save
的实现默认会创建一个事务。请参阅文档了解更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.