Home > Blockchain >  spring jpa findBy column of inside entity
spring jpa findBy column of inside entity

Time:01-07

I have a couple of related entities in a relational DB:

@Entity
public class A {
    @Id
    @Column(name = "id" ...)
    private UUID id;

    @OneToMany(mappedBy = "a")
    private Set<B> bs;
}

and

@Entity
public class B {
    @Id
    @Column(name = "id" ...)
    private UUID id;

    @ManyToOne
    @JoinColumn(name = "a_id")
    private A a;
}

So I have a B Repository

@Repository
public interface BRepository extends JpaRepository<B, UUID> {
    List<B> findByA(A a);
}

And id like to have a query by which I obtain the all Bs with the same A. I'm used to have an a_id column in B, not the whole entity. I don't know how to manage this, nor with a JPA query nor with a NamedQuery.

Many thanks in advance!

Luis

CodePudding user response:

List<B> findByA(A a);

Should work as it is, as ORM vendor already knows which field of A is considered the id. So it will translate the SQL query accordingly so that it looks for objects with the same Id in database as the id of the object that you provide as parameter.

However you should also consider overriding methods equals() and hashCode() of your class A so that they consider the field @Id @Column(name = "id" ...) private UUID id; This could be practically useful if you use collections of HashSet or HashMap containing the class A.

Some more information on why you should override equals() and hashCode() can be found from this SO thread

CodePudding user response:

As already answered, the proposed code should already work but it didn't... The fix that worked for me was

List<B> findByA_Id(UUID id);

Table_Field references field field to table Table.

  •  Tags:  
  • Related