JPA/Hibernate 批量(批量)插入 [英] JPA/Hibernate bulk(batch) insert

查看:54
本文介绍了JPA/Hibernate 批量(批量)插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在阅读有关 jpa 批量插入的几个主题后创建的简单示例,我有 2 个持久对象 User 和 Site.一个用户可以有多个站点,所以我们在这里有一对多的关系.假设我想创建用户并将多个站点创建/链接到用户帐户.考虑到我愿意对 Site 对象使用批量插入,代码如下所示.

Here is simple example I've created after reading several topics about jpa bulk inserts, I have 2 persistent objects User, and Site. One user could have many site, so we have one to many relations here. Suppose I want to create user and create/link several sites to user account. Here is how code looks like, considering my willing to use bulk insert for Site objects.

User user = new User("John Doe");

user.getSites().add(new Site("google.com", user));
user.getSites().add(new Site("yahoo.com", user));

EntityTransaction tx = entityManager.getTransaction();
tx.begin();
entityManager.persist(user);
tx.commit();

但是当我运行此代码时(我使用 hibernate 作为 jpa 实现提供程序)我看到以下 sql 输出:

But when I run this code (I'm using hibernate as jpa implementation provider) I see following sql output:

Hibernate: insert into User (id, name) values (null, ?)
Hibernate: call identity()
Hibernate: insert into Site (id, url, user_id) values (null, ?, ?)
Hibernate: call identity()
Hibernate: insert into Site (id, url, user_id) values (null, ?, ?)
Hibernate: call identity()

所以,我的意思是真正的"批量插入不起作用还是我很困惑?

So, I means "real" bulk insert not works or I am confused?

这是 源代码,用于此示例项目,这是 maven项目,因此您只需下载并运行 mvn install 即可检查输出.

Here is source code for this example project, this is maven project so you have only download and run mvn install to check output.

更新:

经过 Ken Liu 的善意建议,我已禁用站点对象 ID 自动生成:

After Ken Liu kindly advise, I've disabled Site object id auto generation:

    User user = new User("John Doe");
    user.getSites().add(new Site(1, "google.com", user));
    user.getSites().add(new Site(2, "yahoo.com", user));
    entityManager.setFlushMode(FlushModeType.COMMIT);
    EntityTransaction tx = entityManager.getTransaction();
    tx.begin();
    entityManager.persist(user);
    tx.commit();

现在我在调试输出中有以下行:

Now I have following line in debug output:

调试:org.hibernate.jdbc.AbstractBatcher - 执行批量大小:2

DEBUG: org.hibernate.jdbc.AbstractBatcher - Executing batch size: 2

有效!

推荐答案

如果你使用数据库来生成 id,那么 Hibernate 必须执行一个查询来为每个实体生成主键.

If you're using the database to generate ids, then Hibernate has to execute a query to generate the primary key for each entity.

这篇关于JPA/Hibernate 批量(批量)插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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