Home > Back-end >  How to access foreign key and its data in JPA
How to access foreign key and its data in JPA

Time:09-17

I have two entities as follows:

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

Now in my EntityB repo class I am having a method to delete rows of Table EntityB based on EntityA fields.

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

But this query gives me an exception:

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]

CodePudding user response:

Your query seems incorrect. Try below query:

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

CodePudding user response:

You can also JPA Repository:

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