JPA SpringBoot Find by id of related object

Task: Create method to find all objects by field in the related object

Example:

@Entity
@Table(name = "a")
@AllArgsConstructor
@NoArgsConstructor
public class A {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String name;
}

@Entity
@Table(name = "b")
@AllArgsConstructor
@NoArgsConstructor
public class B {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String name;

    @OneToOne
    @JoinColumn(name="aId", referencedColumnName = "aId")
    private A aId;

}

Write method to search all B where B.A.id = value.

Implementation:

@Repository
public interface BRepository extends JpaRepository<B, Long> {
    List<B> findAllByaIdId(String aId);
}

Example for IN case:

@Repository 
public interface BRepository extends JpaRepository<B, Long> {
List<B> findAllByaIdIdIn(Collection<String> aIds);
}

Done.

Leave a Reply

Your email address will not be published. Required fields are marked *




Enter Captcha Here :