创建后不管理JPA @Entity? [英] JPA @Entity not managed after creation?

查看:310
本文介绍了创建后不管理JPA @Entity?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的控制器方法,在其中创建一个新对象Car,然后将其名称设置为Audi:

I have a simple controller method, where I create a new object Car and then set its name to Audi:

@GetMapping(value = "/resource")
public ResponseEntity visit() {
    Car car = carRepo.save(new Car("VolksWagen")); // Car should be managed now?
    car.setName("Audi"); // <-- has no effect on database state

    return ResponseEntity.ok().build();
}

在数据库中,它永远不会成为Audi,而是保持为VolksWagen.

In the database, it never becomes an Audi, but stays a VolksWagen.

为什么会这样?对于持久性上下文,新创建的Car是否不应该处于 managed 状态?

Why does this happen? Shouldn't the newly created Car be in managed state for the persistence context?

注意:如果添加@Transactional批注,它将起作用.我认为如果启用OSIV就足够了.我对OSIV和@Transactional的误解是什么?

Note: It works if I add the @Transactional annotation. I thought it would be enough if OSIV is enabled. What am I misunderstanding about OSIV and @Transactional?

推荐答案

在视图中打开会话(OSIV)使 session 保持打开状态,以便能够懒惰渲染视图时的-load关联.但这不会使交易保持打开状态.

Open Session In View (OSIV) leaves the session open, in order to be able to lazy-load associations when rendering the view. But it doesn't leave the transaction open.

更改已经提交,以后的更改将不会保留,因为以后的更改将被刷新或提交(并且首先不应发生更改)

The changes have already been committed, and later changes won't be persisted since later changes are ever flushed nor committed (and since changes are not supposed to happen in the first place)

OSIV无论如何都是肮脏的,因为在提交事务后加载的数据可能与在事务内部加载的数据不一致.我会避免的.参见 https://vladmihalcea.com/the-open-session-in -view-anti-pattern 的更多原因.

OSIV is a dirty hack anyway, since the data loaded after the transaction is committed is possibly inconsistent with the data loaded inside the transaction. I would avoid it. See https://vladmihalcea.com/the-open-session-in-view-anti-pattern for more reasons.

这篇关于创建后不管理JPA @Entity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆