Home > database >  ConstraintViolationException during transaction for entity with index
ConstraintViolationException during transaction for entity with index

Time:01-30

I have the following entity:

@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;

}

And I'm trying to empty its database table, and insert new rows:

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

ProductRepository is:

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

And 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;
    }

}

Trying to perform the insertion fails with java.sql.BatchUpdateException: ORA-00001: unique constraint (productIndex) violated, but shouldn't the previous deletion make this violation impossible to happen?

CodePudding user response:

According to me, you should perform deleteAll() operation separately as you are using @Transactional annotation and changes are still not committed, due to which your primary keys are still duplicated.

CodePudding user response:

You are getting this error because you put unique contraint in index table named "productIndex"

You are delete records in this line

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

but i thinks records remains in index table named "productIndex"

  • Related