【问题标题】:How to access foreign key and its data in JPA如何在 JPA 中访问外键及其数据
【发布时间】:2021-11-10 20:01:49
【问题描述】:

我有两个实体如下:

public class EntityA
{
    private String id;
    private String entityId;
    private String muscle;
}

public class EntityB
{
    private String id;

    @ManyToOne
    @JoinColumn("entitya_id")
    private EntityA entitya;
}

现在在我的EntityB repo 类中,我有一种方法可以根据 EntityA 字段删除表 EntityB 的行。

@Modifying
@Query("DELETE FROM EntityB WHERE EntityA.entityId=:entityId AND (:muscle IS NULL OR EntityA.muscle=:muscle)")
int deleteEntityByRecords(@Param("entityId")  String entityId, 

@Param("muscle")String muscle);

但是这个查询给了我一个例外:

Error creating bean with name 'EntityBrepo': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract int com.fedex.airops.pilot.bank.PilotBankTransactionRepo.deleteEntityBRecord(java.lang.String,java.lang.String)!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1803) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:

    您的查询似乎不正确。试试下面的查询:

    @Modifying
    @Query("DELETE FROM EntityB eb WHERE eb.entitya.id=:entityId AND (:muscle IS NULL OR eb.entitya.muscle=:muscle)")
    int deleteEntityByRecords(@Param("entityId")  String entityId, @Param("muscle") String muscle);
    

    【讨论】:

    • Jignesh 我已经编辑了帖子,请你看看,并建议我如何解决
    • 您能否发布您在存储库中的确切查询。
    • 是的,我明白了。可能这对你有用 - stackoverflow.com/a/7247124/3709922
    【解决方案2】:

    您还可以使用 JPA 存储库:

    void deleteByIdAndEntityAMuscleIsNullOrEntityAMuscle(@Param("entityId")  String entityId, @Param("muscle") String muscle);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-31
      • 2020-03-15
      相关资源
      最近更新 更多