我有以下实体:
@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
的插入失败,但是前面的删除不应该使这种冲突不可能发生吗?
2条答案
按热度按时间z0qdvdin1#
根据我的意见,您应该单独执行deleteAll()操作,因为您正在使用@Transactional注解,并且更改仍然没有提交,因此您的主键仍然是重复的。
pcww981p2#
出现此错误是因为您在名为“productIndex”的索引表中放置了唯一约束
您正在删除该行记录
但我认为记录保留在名为“productIndex”的索引表中