49

I have the following code:

@Entity
public class StudentEntity {
    @Id
    private String id;
    private Student student;
    ...
}


public class Student {
    private String name;
    private List<Grade> grades;
}


public class Grade {
    private String className;
    private String grade;
}

I've set up a spring data mongodb repository and I'm trying to create a method that will return me a List<Student> based on a className that I pass in as parameter. Based on everything I've read, I assumed that the following would work:

public List<Student> findByStudentGradesClassName(final String className);

but that gives an error saying that the parameter type should be a Grade object. I really only want to pass in a String className.

Is this possible?

Andronicus
  • 25,419
  • 17
  • 47
  • 88
DraegerMTN
  • 1,001
  • 2
  • 12
  • 21

1 Answers1

90

You would have to separate nested fields with underscore:

public List<Student> findByStudent_Grades_ClassName(final String className);

Note, that you still have to start field names with uppercase.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
  • 7
    Using Spring boot 2.1.8 / spring data 2.1.10 I found the underscores are not necessary. Tested on a @ManyToOne (so not a list) nested field and using a countAll... statement in the repository. – BitfulByte Oct 15 '19 at 10:27
  • 9
    Underscore still comes in handy, for example if you have X.myName and X.MY.name relations. I know it is uncommon scenario but I have a requirement to duplicate value both in X and in related component. Both will match FindByMyName thus error. Fortunetly FindByMy_Name wokrs as expected then. – Antoniossss Oct 23 '19 at 17:09
  • 4
    Sonarqube does not like underscores in a method name. – Akash Sep 16 '20 at 11:41
  • 4
    @Akash the rule can always be disabled, it's more readable, because you clearly see the level in your hierarchy – Andronicus Sep 16 '20 at 12:12