如何使用Spring数据JPA显示来自多个表的数据 - 多对多关系

时间:2017-08-14 14:15:42

标签: spring spring-data-jpa jpql jpa-criteria

我正在尝试从Spring Data JPA中的多个表中获取数据。

我有:

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;

这些实体生成名为“classes_professor”的表,并将字段生成如下classes_id和professor_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);
    }

当我尝试运行它时出现此错误:

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]

1 个答案:

答案 0 :(得分:2)

错误在于p.Classes。它应该是p.classes,因为你的POJO教授的属性是用小写字母写的。

查询检查教授POJO /实体的属性;它不会寻找其他实体名称。

在上面: 有时候你会写“教授”其他时候“教授”。