Java 使用JPA/EJB3的批插入

Java 使用JPA/EJB3的批插入,java,hibernate,orm,jpa,batch-insert,Java,Hibernate,Orm,Jpa,Batch Insert,JPA/EJB3框架是否提供了执行批插入操作的标准方法。。。? 我们使用hibernate作为持久性框架,所以我可以回到hibernate会话并使用组合会话。save()/Session.flush()实现批插入。但是想知道EJB3是否支持这一点…对于hibernate,具体来说,整个过程将解释这些方法 但是您的意思是希望EJB方法通过Hibernate实现,因此实体管理器文档中也有一章介绍了这一点。我建议您同时阅读(核心和实体经理) 在EJB中,它只是关于使用EJB-QL(有一些限制)。如果您

JPA/EJB3框架是否提供了执行批插入操作的标准方法。。。?
我们使用hibernate作为持久性框架,所以我可以回到hibernate会话并使用组合会话。save()/Session.flush()实现批插入。但是想知道EJB3是否支持这一点…

对于hibernate,具体来说,整个过程将解释这些方法

但是您的意思是希望EJB方法通过Hibernate实现,因此实体管理器文档中也有一章介绍了这一点。我建议您同时阅读(核心和实体经理)


在EJB中,它只是关于使用EJB-QL(有一些限制)。如果您需要更大的灵活性,Hibernate提供了更多的机制。

是的,如果您想要定义控件,您可以回滚到JPA实现

JPA1.0在EL-HQL方面很丰富,但在标准API支持方面却很少,但这一点在2.0中已经得到了解决

Session session = (Session) entityManager.getDelegate();
session.setFlushMode(FlushMode.MANUAL);

JPA和Hibernate都不提供对批插入的特定支持,使用JPA进行批插入的习惯用法与使用Hibernate相同:

EntityManager em = ...;
EntityTransaction tx = em.getTransaction();
tx.begin();

for ( int i=0; i<100000; i++ ) {
    Customer customer = new Customer(.....);
    em.persist(customer);
    if ( i % 20 == 0 ) { //20, same as the JDBC batch size
        //flush a batch of inserts and release memory:
        em.flush();
        em.clear();
    }
}

tx.commit();
session.close();
EntityManager em=。。。;
EntityTransaction tx=em.getTransaction();
tx.begin();
对于(int i=0;iPascal

在您的示例中,插入100000条记录是在单个事务中完成的,因为commit()只在最后被调用..这会给数据库带来很大压力吗?此外,如果发生回滚,成本将过高

以下方法会更好吗

EntityManager em = ...;
for ( int i=0; i<100000; i++ ) {
   if(!em.getTransaction().isActive()) {
      em.getTransaction().begin();
   }
   Customer customer = new Customer(.....);
   em.persist(customer);
   if ((i+1) % 20 == 0 ) { //20, same as the JDBC batch size
      //flush and commit of inserts and release memory:
      em.getTransaction().commit(); 
      em.clear();
   }
}

session.close();
EntityManager em=。。。;

对于(int i=0;i和介质记录编号,您可以使用以下方式:

em.getTransaction().begin();
for (int i = 1; i <= 100000; i++) {
     Point point = new Point(i, i);
     em.persist(point);
     if ((i % 10000) == 0) {
          em.flush();
          em.clear();
     }
}
em.getTransaction().commit();
em.getTransaction().begin();

对于(int i=1;i仅用于健全性检查),您的
if
语句应为
i>0&&i%20==0
,否则它将在添加第一个元素后立即刷新(并清除)。
em.getTransaction().begin();
for (int i = 1; i <= 1000000; i++) {
      Point point = new Point(i, i);
      em.persist(point);
      if ((i % 10000) == 0) {
          em.getTransaction().commit();
          em.clear();          
          em.getTransaction().begin();
      }
}
em.getTransaction().commit();