简体   繁体   中英

Spring JPA Repository findBy foreign key directly with POJO instead of data member of class

I have a Paper entity and Student entity defined as below
Paper.java

public class Paper extends BaseEntity
{
    ...

    @ManyToOne
    @JoinColumn(name = "student", nullable = false, referencedColumnName = "tp")
    private Student student;

    ...
}

Student.java

public class Student extends BaseEntity
{
    ...
}

I create a PaperRepository for Paper class, I want to find Paper by Student, so a query method is created as this:

List<Paper> findByStudentOrderByDateSubmitted(Student student);

But this method returns an empty result. I have to specify the method to find by student id like below:

List<Paper> findByAndStudent_IdOrderByDateSubmitted(String id);

With this method, it works. Is it possible to find by foreign class, instead of the data member of the foreign class?

try below :

@ManyToOne
@JoinColumn(name = "STUDENT_ID", nullable = false, referencedColumnName = "tp")
private Student student;

At least it's possible using @Query.

@Query("select p from Paper p where p.student.id = :student.id order by p.student.dateSubmitted")
List<Paper> findByStudentOrderByDateSubmitted(@Param("student") Student student);

UDP

And do you mean it's possible or impossible, or "Is it possible to find by foreign class, instead of the data member of the foreign class?"? :) Above example shows it's possible in your case.

Generally, yes it's possible and findByStudent(Student student) should work. But in some cases results of parser's algorithm could be ambigious and you can use underscore symbol to say where parser should split properties. My guess it's your case (if you could show full POJOs it might be helpfull and I can say more).

You could read about parser's algorithm here, for example, - https://docs.spring.io/spring-data/jpa/docs/1.11.6.RELEASE/reference/html/#repositories.query-methods.query-property-expressions . There you also can find recommendation don't use underscore symbol as it breaks Java conventions, so sometimes @Query could be better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM