jpa 具有索引的实体在事务处理期间发生ConstraintViolationException

cigdeys3  于 2023-01-31  发布在  其他
关注(0)|答案(2)|浏览(129)

我有以下实体:

@Entity
@Table(name = "product",
        indexes = {@Index(name = "productIndex", columnList = "family, group, type", unique = true)})
public class Product implements Serializable {

    @Id
    @Column(name = "id")
    private Long id;

    @Column(name = "family")
    private String family;

    @Column(name = "group")
    private String group;

    @Column(name = "type")
    private String type;

}

我尝试清空它的数据库表,并插入新行:

@Transactional
public void update(List<Product> products) {
    productRepository.deleteAll();
    productRepository.batchInsert(products);
}

ProductRepository为:

public interface ProductRepository extends JpaRepository<Product, Long>, BatchRepository<Product> { }

BatchRepository

@Repository
public class BatchRepository<T> {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public int batchInsert(List<T> entities) {
        int count = 0;

        for (T entity : entities) {
            entityManager.persist(entity);
            count++;

            if (count % 2000 == 0) {
                entityManager.flush();
                entityManager.clear();
            }
        }

        entityManager.flush();
        entityManager.clear();

        return count;
    }

}

尝试执行java.sql.BatchUpdateException: ORA-00001: unique constraint (productIndex) violated的插入失败,但是前面的删除不应该使这种冲突不可能发生吗?

z0qdvdin

z0qdvdin1#

根据我的意见,您应该单独执行deleteAll()操作,因为您正在使用@Transactional注解,并且更改仍然没有提交,因此您的主键仍然是重复的。

pcww981p

pcww981p2#

出现此错误是因为您在名为“productIndex”的索引表中放置了唯一约束
您正在删除该行记录

@Transactional
public void update(List<Product> products) {
 productRepository.deleteAll();
 productRepository.batchInsert(products);
}

但我认为记录保留在名为“productIndex”的索引表中

相关问题