gpt4 book ai didi

java - Controller 在进行 spring/hibernate 调用时会阻塞吗?

转载 作者:行者123 更新时间:2023-12-01 10:11:34 24 4
gpt4 key购买 nike

这是从 Play 和 Spring 示例的激活器模板创建项目后的 Controller 。

Controller 代码:

@org.springframework.stereotype.Controller
public class Application {

@Autowired
private BarService barService;

public Result addBar() {
Form<Bar> form = Form.form(Bar.class).bindFromRequest();
Bar bar = form.get();
barService.addBar(bar);
return play.mvc.Controller.redirect(controllers.routes.Application.index());
}
}

酒吧服务:

@Service
@Transactional
public class BarServiceImpl implements BarService {

@PersistenceContext
EntityManager em;

@Override
public void addBar(Bar bar) {
em.persist(bar);
}

@Override
public List<Bar> getAllBars() {
CriteriaQuery<Bar> c = em.getCriteriaBuilder().createQuery(Bar.class);
c.from(Bar.class);
return em.createQuery(c).getResultList();
}
}

Spring Hibernate 配置:

@Configuration
@EnableTransactionManagement
public class DataConfig {

@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setPackagesToScan("models");
entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setJpaPropertyMap(new HashMap<String, String>(){{
put("hibernate.hbm2ddl.auto", "create-drop");
}});
entityManagerFactory.afterPropertiesSet();
return entityManagerFactory.getObject();
}

@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager(entityManagerFactory());

return transactionManager;
}

@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Play.application().configuration().getString("db.default.driver"));
dataSource.setUrl(Play.application().configuration().getString("db.default.url"));
return dataSource;
}
}

我的问题是,当 Controller 调用 barService 中的 addBar 函数时,它是阻塞调用吗?如果是,那么考虑到它是来自 Typesafe 激活器本身的示例代码,那么在 Play 应用程序中进行 spring/hibernate 集成的正确方法应该是什么。

最佳答案

是的,它会阻塞,因为 JDBC 没有异步/非阻塞支持。由于 Hibernate 依赖于 JDBC,因此它继承了它的阻塞行为。这也是documented here :

Common examples of such blocking operations are JDBC calls, streaming API, HTTP requests and long computations.

我强烈建议您阅读以下文档页面:

  1. JavaAsync: Handling asynchronous results
  2. Understanding Play thread pools

我还建议您在这里查看其他非常类似的讨论:

  1. https://stackoverflow.com/a/32784410/4600

关于java - Controller 在进行 spring/hibernate 调用时会阻塞吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36097699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com