Satscreate
Satscreate

Reputation: 535

How to filter based on One to many & Many to One relations table Spring JPA

I have a table Student which is one to many with Address table and Address have many to one relation to Student table.

public class Student{
  @Id
  @Column(name = "stud_id", nullable = false)
  private String stud_id;
  @Column(name = "stud_name", nullable = false)
  private String stud_name;
  @OneToMany(mappedBy = "student")
  private List<Address> addresses;
}

public class Address{
  @Id
  @Column(name = "address_id", nullable = false)
  private String address_id;
  @Column(name = "address_name", nullable = false)
  private String address_name;
  @ManyToOne
  @JoinColumn(name = "stud_id", nullable = false)
  private Student student;
}

How do i filter something like get All Student addresses address_name in 'Something'. Expected return should be Student object so that i can traverse into Address which is filtered as 'Something' using Spring JPA repository with SpringConvention or by @Query. Please help

Upvotes: 0

Views: 1225

Answers (1)

tremendous7
tremendous7

Reputation: 751

try this if you have a collection of addressNames to filter against

@Query("select a.student from Address a where a.address_name in (?1)")
List<Student> findStudentsByAddressNameIn(List<String> addressNames);

or if you want to filter by address_name = 'something'

@Query("select a.student from Address a where a.address_name = ?1")
List<Student> findStudentsByAddressName(String addressNameFilter);

or if you want to filter by address_name contains 'something' set addressNameFilter to "%" + addressNameFilter + "%" and use

@Query("select a.student from Address a where a.address_name like ?1")
List<Student> findStudentsByAddressNameLike(String addressNameFilter);

Upvotes: 1

Related Questions