简体   繁体   English

如何在Play JPA中保存对象列表

[英]How to save a List of objects in Play JPA

I have a LinkedBlockingQueue, and I would like to save all the elements to the database. 我有一个LinkedBlockingQueue,我想将所有元素保存到数据库中。 I know I can save it one by one: 我知道我可以一个一个地保存它:

ObjectModel om = new ObjectModel();
om.save();

However, that means I have to loop through all the elements and do a new connection for each. 但是,这意味着我必须循环遍历所有元素并为每个元素建立新连接。 Can I insert the entire list at once? 我可以一次插入整个列表吗?

In play 1.x, when the server receives a request, play/jpa will open a transaction to you database. 在play 1.x中,当服务器收到请求时,play / jpa将向您的数据库打开一个事务。 This transaction will automatically be rolled back if anything goes wrong, else it automatically commits when the response is sent to the client. 如果出现任何问题,此事务将自动回滚,否则在响应发送到客户端时会自动提交。

Therefor, even if you loop through your JPA entities and call save() on them one after another, they will all be executed with the same connection in the same transaction. 因此,即使您遍历JPA实体并一个接一个地调用它们上的save(),它们也将在同一事务中使用相同的连接执行。

I would think it works the same way in Play 2, but honestly, I don't know. 我认为它在Play 2中的工作方式相同,但老实说,我不知道。

The simple answer will not NO. 简单的答案不会是NO。 Some one down the line will have to execute insert query for all individual objects. 线下的某个人必须对所有单个对象执行插入查询。

You do not have to create new connection for each insert. 您不必为每个插入创建新连接。 You should create a connection and fire insert on the same connection in each iteration. 您应该在每次迭代中在同一连接上创建连接和触发插入。

Maybe this question gets you further. 也许这个问题会让你更进一步。 If you know how to do what you want on the underlying DB, you also could use a native query (which you can create via the EntityManager), I suppose. 如果您知道如何在底层数据库上执行您想要的操作,我还可以使用本机查询(您可以通过EntityManager创建)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM