5

I have two entities:

  1. User (it has field String userName);
  2. School (it has field Long id);

In School I have:

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = User.class)
@JoinColumn(name = "schoolId")
private List<User> users;

In User I have:

@ManyToOne(optional = false, targetEntity = School.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "schoolId", referencedColumnName = "id", nullable = false)
private School school;

I also have SchoolRepository:

public interface SchoolRepositoryextends CrudRepository<School, Long> {
}

And I want to make a request to database by JPA query method names. For example, I want to find all users with name John in school with id = 1. How can I do this via SchoolRepository?

The only thing that comes to my mind is findByIdAndUsersUserName, but it gives me the exception that there's no field named users in my schools table.

NOTE:

of course, it is possible via @Query but I wonder if there's a way to do it via method names.

htshame
  • 6,599
  • 5
  • 36
  • 56
  • 1
    are you referring to spring data jpa? https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.details – PDStat Apr 12 '18 at 09:45
  • Indeed, that is not the JPA API. It is SPRING. SPRING DATA JPA != JPA API –  Apr 12 '18 at 09:48
  • Yes, you're right, thank you. – htshame Apr 12 '18 at 09:48
  • You can do it only in UsersRepository. selectByNameAndSchool – Den B Jun 07 '18 at 10:53
  • @DenB `And` keyword is for `and`ing the multiple condition for where. check 6.3.2 from https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.repositories – Ratul Sharker Nov 24 '20 at 16:11

0 Answers0