gpt4 book ai didi

java - 所有代码是否在同一 session 中的 mvc Controller 方法内运行?

转载 作者:行者123 更新时间:2023-12-02 09:08:11 24 4
gpt4 key购买 nike

我有以下模型:

实体FooBar之间的多对多。 Foo 有一个 Bar 的 LinkedHashSet,并用 @OrderBy 注释。

Controller 包含一个方法,该方法首先将新的 Bar 保存到集合中,然后从一个 Foo 获取所有 Bar。

Set<Bar> methodName(FooId fid, Bar b){
fooService.addBar(fid, b);
return fooService.getBarsOfFoo(fid);
}

服务方式:

@Transactional
void addBar(UUID fid, Bar b){
Foo f = fooRepository.getFoo(fid);
f.getBars().add(b);
}

@Transactional(readOnly = true)
Set<Bar> getBarsOfFoo(UUID fid){
return fooRepository.getFoo(fid).getBars();
}

问题是,当调用该方法时,除了最后引入的一个之外,所有的 Bar 都会被排序。我认为这与 hibernate 一级缓存有关,但我不确定与该方法关联的 session 何时开始或结束。

该 Controller 方法中的两个 session 方法是否在同一 session 中运行?

最佳答案

Hibernate session 与官方文档 https://developer.jboss.org/wiki/SessionsAndTransactions 中的 MVC Controller session 不同。

这取决于您的配置以及创建此 session 的人员和方式

但原则上有3种模式

每个请求的 session

the session-per-request implementation pattern. A single Session and a single database transaction implement the processing of a particular request event (for example, a Http request in a web application). Do never use the session-per-operation anti-pattern! (There are extremely rare exceptions when session-per-operation might be appropriate, you will not encounter these if you are just learning Hibernate.)

每个请求与分离对象的 session

Once persistent objects are considered detached during user think-time and have to be reattached to a new Session after they have been modified.

每次对话 session

In this case a single Session has a bigger scope than a single database transaction and it might span several database transactions. Each request event is processed in a single database transaction, but flushing of the Session would be delayed until the end of the conversation and the last database transaction, to make the conversation atomic. The Session is held in disconnected state, with no open database connection, during user think-time. Hibernate's automatic optimistic concurrency control (with versioning) is used to provide conversation isolation.

因此,查看文档时您可能会使用每次 session session ,因此可能需要在下次调用之前刷新 session 。

关于java - 所有代码是否在同一 session 中的 mvc Controller 方法内运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59629030/

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