DeleteById() 使用 JPA 抛出 JdbcSQLIntegrityConstraintViolationException

问题描述 投票:0回答:1

我正在学习spring并使用jpa和h2数据库。当我尝试使用 JpaRepository 中的 deleteById() 方法删除 时,然后出现 JdbcSQLIntegrityConstraintViolationException。请帮助我如何解决这个问题。我提前将数据加载到数据库中。

沙威玛课程

@Data
@Entity
@Table(name = "shawarma")
public class Shawarma {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @Column(name = "created_at")
    private Date createdAt = new Date();

    @NotNull
    @Size(min = 5, message = "Name must be at least 5 characters long")
    @Column(name = "name")
    private String name;

    @Size(min = 1, message = "You must choose at least 1 ingredient")
    @ManyToMany(fetch = FetchType.EAGER)
    private List<Ingredient> ingredients = new ArrayList<>();

    public void addIngredient(Ingredient ingredient) {
        this.ingredients.add(ingredient);
    }
}

成分类别

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
@Table(name = "ingredient")
public class Ingredient {

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

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

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

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


    public enum Type {
        PITA, PROTEIN, VEGGIES, CHEESE, SAUCE
    }
}

在表中加载数据

public CommandLineRunner dataLoader(
            IngredientRepository ingredientRepo,
            UserRepository userRepo,
            PasswordEncoder encoder,
            ShawarmaRepository shawarmaRepo) {
        return args -> {
            Ingredient originalLavash = new Ingredient(1L, "ORIG", "Original lavash", Ingredient.Type.PITA);
            Ingredient cheeseLavash = new Ingredient(2L, "CHES", "Cheese lavash", Ingredient.Type.PITA);
            Ingredient chicken = new Ingredient(3L, "CHIC", "Chicken", Ingredient.Type.PROTEIN);
            Ingredient shrimps = new Ingredient(4L, "SHRI", "Shrimps", Ingredient.Type.PROTEIN);
            Ingredient tomato = new Ingredient(5L, "TMTO", "Tomato", Ingredient.Type.VEGGIES);
            Ingredient lettuce = new Ingredient(6L, "LETC", "Lettuce", Ingredient.Type.VEGGIES);
            Ingredient yes = new Ingredient(7L, "YES", "Yes", Ingredient.Type.CHEESE);
            Ingredient no = new Ingredient(8L, "NO", "No", Ingredient.Type.CHEESE);
            Ingredient adjika = new Ingredient(9L, "ADJ", "Adjika", Ingredient.Type.SAUCE);
            Ingredient moreSauce = new Ingredient(10L, "MORE", "More sauce", Ingredient.Type.SAUCE);

            ingredientRepo.save(originalLavash);
            ingredientRepo.save(cheeseLavash);
            ingredientRepo.save(chicken);
            ingredientRepo.save(shrimps);
            ingredientRepo.save(tomato);
            ingredientRepo.save(lettuce);
            ingredientRepo.save(yes);
            ingredientRepo.save(no);
            ingredientRepo.save(adjika);
            ingredientRepo.save(moreSauce);

删除映射

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteIngredient(@PathVariable("id") Long ingredientId) {
        ingredientRepo.deleteById(ingredientId);
    }

异常

org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Нарушение ссылочной целостности: "FKT6WP53NXWTEOF9GJX5AO0AG8: PUBLIC.SHAWARMA_INGREDIENTS FOREIGN KEY(INGREDIENTS_ID) REFERENCES PUBLIC.INGREDIENT(ID) (CAST(2 AS BIGINT))"
Referential integrity constraint violation: "FKT6WP53NXWTEOF9GJX5AO0AG8: PUBLIC.SHAWARMA_INGREDIENTS FOREIGN KEY(INGREDIENTS_ID) REFERENCES PUBLIC.INGREDIENT(ID) (CAST(2 AS BIGINT))"; SQL statement:
delete from ingredient where id=? [23503-224]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:520) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:489) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.message.DbException.get(DbException.java:223) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.message.DbException.get(DbException.java:199) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:365) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.constraint.ConstraintReferential.checkRowRefTable(ConstraintReferential.java:382) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.constraint.ConstraintReferential.checkRow(ConstraintReferential.java:256) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.table.Table.fireConstraints(Table.java:1200) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.table.Table.fireAfterRow(Table.java:1218) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.command.dml.Delete.update(Delete.java:92) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.command.dml.DataChangeStatement.update(DataChangeStatement.java:74) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.command.CommandContainer.update(CommandContainer.java:169) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.command.Command.executeUpdate(Command.java:256) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:216) ~[h2-2.2.224.jar:2.2.224]
    at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:174) ~[h2-2.2.224.jar:2.2.224]
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-5.1.0.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-5.1.0.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:194) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.engine.jdbc.mutation.internal.AbstractMutationExecutor.performNonBatchedMutation(AbstractMutationExecutor.java:134) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.engine.jdbc.mutation.internal.MutationExecutorSingleNonBatched.performNonBatchedOperations(MutationExecutorSingleNonBatched.java:55) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.engine.jdbc.mutation.internal.AbstractMutationExecutor.execute(AbstractMutationExecutor.java:55) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.persister.entity.mutation.AbstractDeleteCoordinator.doStaticDelete(AbstractDeleteCoordinator.java:279) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.persister.entity.mutation.AbstractDeleteCoordinator.delete(AbstractDeleteCoordinator.java:87) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.action.internal.EntityDeleteAction.execute(EntityDeleteAction.java:131) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:632) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:499) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:371) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:41) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:127) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1425) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:487) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:2324) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:1981) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:439) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:169) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:267) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-6.5.2.Final.jar:6.5.2.Final]
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:562) ~[spring-orm-6.1.12.jar:6.1.12]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:795) ~[spring-tx-6.1.12.jar:6.1.12]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:758) ~[spring-tx-6.1.12.jar:6.1.12]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:663) ~[spring-tx-6.1.12.jar:6.1.12]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:413) ~[spring-tx-6.1.12.jar:6.1.12]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-6.1.12.jar:6.1.12]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.1.12.jar:6.1.12]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:138) ~[spring-tx-6.1.12.jar:6.1.12]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.1.12.jar:6.1.12]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:165) ~[spring-data-jpa-3.3.4.jar:3.3.4]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.1.12.jar:6.1.12]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-6.1.12.jar:6.1.12]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.1.12.jar:6.1.12]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:223) ~[spring-aop-6.1.12.jar:6.1.12]
    at jdk.proxy4/jdk.proxy4.$Proxy145.deleteById(Unknown Source) ~[na:na]

我尝试更改@ManyToMany的参数,但没有任何帮助

java jpa many-to-many
1个回答
0
投票

很简单,你的实体“Shawarma”取决于其记录中的实体“Ingredient”,如果你想删除某个成分,你需要验证它不属于任何“Shawarma”

© www.soinside.com 2019 - 2024. All rights reserved.