且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

插入时如何忽略重复行

更新时间:2023-01-22 16:40:20

数据库样式选项

Hibernate不提供将插入的选项添加到语句中。我不知道MS SQL是否有相同的选项。

Hibernate does not offer to add an option to its insert into statements. And I don't know if the same option is available for MS SQL.

但是如果你找到这样的选项,你可以拦截insert语句并自己添加:

But if you find such an option, you can intercept the insert statement and add that yourself:

public class IgnoreRowOnDupInterceptor extends EmptyInterceptor {

  public String onPrepareStatement(String sql) {
    if (sql.startsWith("insert into avaya_cm_cdr") {
      return sql.replace("insert into", 
        "insert /*+ ignore_row_on_dupkey_index(avaya_cm_cdr, i_avaya_cm_cdr_nodub) */ into");
    }
    return sql;
  }

} 

您需要在 persistence.xml中声明此拦截器

<property name="hibernate.ejb.interceptor" value="...IgnoreRowOnDupInterceptor" />

JPA样式选项

您可以记住上次解析的最后一行(或从数据库中检索它)并跳过档案联合国直到那条线。在这种情况下,您甚至可以节省一次又一次地解析每个现有项目的时间。

You could remember the last line from the last parsing (or retrieve it from the database) and skip the file until that line. In that case you even would save the time to parse every existing item again and again.

从我的角度来看,这是JPA方式,因为您通常只将数据库用作存储,并将业务逻辑保留在(Java)应用程序中。

From my point of view this is the JPA way, because you usually use the database only as storage and keep the business logic in the (Java) application.