Java Spring JPA:Save() 方法是否应该将数据提交到数据库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35651757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:58:11  来源:igfitidea点击:

Spring JPA: Should the Save() method commit data to the database?

javaspringrepositoryspring-dataspring-data-jpa

提问by java123999

I am using Spring datafor my project, I am using a Standard Repositorythat extends CRUD Repository.

我正在Spring data为我的项目使用,我使用的标准Repositoryextends CRUD Repository.

My code is working as expected, however when I call repository.save()the database is notaltered?

我的代码按预期工作,但是当我调用repository.save()数据库时没有改变?

Do I also need to then call a commitafter this in order to alter the Database? Or should the repository.save()method be altering the database automatically?

我是否还需要commit在此之后调用 a以更改数据库?或者该repository.save()方法应该自动更改数据库?

采纳答案by Hans Poo

When your application runs, the Entity Manager associated with the thread keeps control of modified or added objects, the save() method just do this, it's a mark that says: "this should be saved in the database".

当您的应用程序运行时,与线程关联的实体管理器保持对修改或添加对象的控制,save() 方法只是这样做,它是一个标记,表示:“这应该保存在数据库中”。

The database DML (insert,update,delete) is not sent to the database while you save things, it's done at the end just before commit, it's delayed to the last moment.

数据库 DML(插入、更新、删除)不会在您保存内容时发送到数据库,它会在最后提交之前完成,它会延迟到最后一刻。

It's possible the send the DML to the database anytime you like using the Entity Manager's flush() method, in fact you can debug the database log and see your queries going through, but this changes to the database will only be visible within your DB connection until the commit is issued; commit() is a method of the transaction associated to the Entity Manager.

可以随时使用实体管理器的 flush() 方法将 DML 发送到数据库,实际上您可以调试数据库日志并查看查询的过程,但是对数据库的这种更改仅在您的数据库连接中可见直到提交提交;commit() 是与实体管理器关联的事务的方法。

In some frameworks like play 1.4.x the commits is issued after the response view is correctly parsed and rendered.

在像 play 1.4.x 这样的一些框架中,提交是在响应视图被正确解析和呈现后发出的。

Bye, Hans

再见,汉斯