Spring Boot中的无状态会话

时间:2016-12-01 11:20:31

标签: hibernate jpa spring-boot

我们有一些REST调用,它们对数据执行大量操作(但不是通过Spring-Data)。因此,我们希望为他们举办无状态会议。

问题是如何在Spring Boot with Hibernate和JPA中正确使用它? 因为当我调用某个存储库时进行简单的测试:

@Repository 
public class HelloRepository {

  @PersistenceContext   
  private EntityManager entityManager;

  public boolean checkIfTransactionIsOpened() {
    return entityManager.unwrap(Session.class).isOpen();   
  }

}

它让我永远是真的。我觉得那里的会话不应该打开,因为我想使用无状态会话。

控制器和服务没有做任何特别的事情。没有@Transactional注释等:

@SpringBootApplication
public class DemoApplication {
  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

@RestController
public class HelloRest {
  @Autowired
  private HelloService helloService;

  @GetMapping("/hello")
  public ResponseEntity<Boolean> sayHello() {
    return ResponseEntity.ok(helloService.checkIfTransactionIsOpened());
  }
}

@Service
public class HelloService {
  @Autowired
  private HelloRepository helloRepository;

  public boolean checkIfTransactionIsOpened() {
    return helloRepository.checkIfTransactionIsOpened();
  }
}

所以问题是:如何通知我的应用“请不要在那里打开会话我想使用无状态会话”?

1 个答案:

答案 0 :(得分:2)

将以下内容添加到application.properties

spring.jpa.open-in-view=false

我们正在考虑switching that to false by default in Spring Boot 2.0