Search code examples
springspring-data-jpajpqljpa-criteria

How to display data from multiple tables using Spring data JPA - many to many relation


I am trying to get data from multiple tables in Spring Data JPA.

I have:

Professor.java

@Entity
public class Professor {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private Long id;
  private String username;

    private String password;

    private String firstname;

    private String lastname;

//Generated getters and setters

  @ManyToMany(mappedBy = "professors", fetch = FetchType.EAGER, cascade = { CascadeType.MERGE, CascadeType.PERSIST })
    private List<Classes> classes;

Classes.java

@Entity
public class Classes {

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

    private String name;

    @Lob
    private String description;

 @ManyToMany(fetch = FetchType.LAZY, cascade = { CascadeType.MERGE, CascadeType.PERSIST })
    private List<Professor> professors;

These entities generate table named as 'classes_professor' and fields as following classes_id and professor_id

I am trying to display professor with some ID that has been given class with some ID.

ClassesRepository.java

@Repository
public interface ClassesRepository extends CrudRepository<Classes,Long>{

    @Query("SELECT p FROM Professor p join p.Classes c WHERE c.id =:id")
    public List<Professor> findProfessorNameById(@Param("id") long id);
}

Controller.java

public List<Professor> findProfessorNameById(@Param("id") long id){
        return classesRepository.findProfessorNameById(id);
    }

When I try to run it I have this error:

could not resolve property: Classes of: com.oggi.model.Professor [SELECT p FROM com.oggi.model.Professor p join p.Classes c WHERE c.id =:id]

Solution

  • The error lies in p.Classes. It should rather be p.classes since the attribute in your Professor POJO is written in lowercase.

    The Query checks the attributes of the Professor POJO / Entity; it does not look for other Entity names.

    On top: Sometimes your are writing "profesor" other times "professor".