如何使用 Guice 和 Jersey 在 GET 请求中配置只读事务?

发布于 2024-12-08 15:27:11 字数 118 浏览 3 评论 0原文

我正在使用 Guice、Guice Persist、Hibernate 和 Jersey。除了用 @GET 注释的方法之外,我所有的资源方法都用 @Transactional 注释。这是配置每个请求的事务范围的正确方法吗?

I am using Guice, Guice Persist, Hibernate and Jersey. All my resource methods are annotated with @Transactional except for the methods that are annotated with @GET. Is this the correct way configure the transaction-per-request scope?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

dawn曙光 2024-12-15 15:27:11

没有“正确”的方法;这取决于您想要实现的目标。回答您的问题涉及几个单独的问题,如下所述。

  1. 数据访问模式:企业 Java 中的传统模式是让控制器调用处理持久性的 DAO(数据访问对象)。在此模式中,您的事务注释将放置在 DAO 方法上,而不是控制器方法上。然而,许多人发现 DAO 太过杀伤力,并且更喜欢将实体管理器注入到控制器中。这是一个完全可以接受的替代方案,据我所知,这就是您选择的方法。
  2. 线程安全:您必须意识到实体管理器实例不是线程安全的,因此您的控制器不能是单例并且必须是请求范围的。换句话说,您无法在多个请求之间共享实体管理器,因此您必须将控制器设置为重新创建,并为每个请求注入一个新的实体管理器。
  3. 事务:如果您的数据检索操作只需要一个查询,则不需要事务。然而,构建完整的对象图通常需要许多查询。在这种情况下,您的检索必须是事务性的,以保证一致性,因为数据可能在查询之间发生变化。某些框架实际上要求所有数据库访问都是事务性的,否则实体管理器将无法正确注入。

总之,只要您的控制器处于请求范围内,您的数据访问模式就很好。但是,如果创建对象图时涉及许多查询,则“GET”函数应该是事务性的。

There is no "correct" way; it depends on what you are trying to achieve. There is a few separate issues involved in answering your question, as discussed below.

  1. Data access pattern: The traditional pattern in enterprise Java is to have your controllers make calls to DAOs (Data Access Objects), which handle persistence. In this pattern, your transaction annotations would be placed on the DAO methods, not your controller methods. However, many people find DAOs to be overkill and prefer to have the entity manager injected into the controller. This is a perfectly acceptable alternative and, from what I can tell, this is the approach you have chosen.
  2. Thread safety: You must be aware that entity manager instances are not thread safe, so your controllers must not be singletons and must be request-scoped. In other words, you cannot share an entity manager across multiple requests, so you must set your controllers to be re-created and have a new entity manager injected for every request.
  3. Transactions: If your data retrieval operation only requires one query, you will not require a transaction. However, building a complete object graph generally requires many queries. In this circumstance, your retrieval must be transactional in order to guarantee consistency, because the data might change between queries. Some frameworks will actually require all database access to be transactional, or the entity manager will not be injected correctly.

In summary, your data access pattern is fine, as long as your controllers are request-scoped. However, your "GET" functions should be transactional if many queries will be involved in creating the object graph.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文