0

I am trying to get main parent entity through child entities by the query. My entities looks like below.

Main parent entity

@Entity
@Data
@EqualsAndHashCode(callSuper = true)
Public class Buyer{
    
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    List<Account> accounts;
    
}

Account class

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Account{
}

Account class gets inherited in below class

@Entity
@Data
@EqualsAndHashCode(callSuper = true)
@DiscriminatorValue("buyer1")
public class BuyerAccount1 extends Account {
    @Column(unique = true)
    private UUID buyerId;

}

I want to obtain Optional by resourceId present BuyerAccount1. I have tried the below JPA query to do that but I am getting Optional.empty() in response.

@Query("SELECT pb \n" +
            " FROM Buyer pb join pb.accounts a \n" +
            " WHERE  a.buyerId= :buyerId \n" +
            " AND type(a) = BuyerAccount1")
    Optional<Buyer> findByBuyerAccount1(@Param("buyerId") UUID buyerId);

Am I missing something in a query?

Thanks in advance!!

Anamika
  • 11
  • 4

1 Answers1

0

I would suggest you use a query like this instead:

@Query("SELECT pb \n" +
        " FROM Buyer pb \n" +
        " WHERE EXISTS (SELECT 1 FROM pb.accounts a WHERE a.buyerId = :buyerId)")
Optional<Buyer> findByBuyerAccount1(@Param("buyerId") UUID buyerId);

Apart from that, if you are using MySQL, you need to specify a length for the UUID type as it is generated as binary(255) by default which will lead to padding the value. Use @Column(length = 16)

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58