如何在多对多关联表上编写查询

时间:2018-04-27 05:56:29

标签: java sql hibernate spring-boot jpa

我有2个实体,我们之间有很多关系。我想在关联表上写一个查询。

Here are the two entities. Craftsmen and Skill.
I want to write a query which selects all Craftsmen with a given skill. 

    @Entity
    @Table(name = "craftsman")
    public class Craftsman {

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

        @ManyToMany
        @JoinTable(name = "craftman_skill", joinColumns = @JoinColumn(name = "craftman_id", referencedColumnName = "id"), 
            inverseJoinColumns = @JoinColumn(name = "skill_id", referencedColumnName = "id"))
        private List<Skill> skillList;
    }
        @Entity
        @Table(name = "skill")
        public class Skill {
            @ManyToMany(mappedBy = "skillList")
            @JsonBackReference
            private List<Craftsman> craftmanList;
        }

以下是我的尝试:

@Query("SELECT c FROM Craftsman c JOIN c.skillList sl WHERE c.skillList.skill_id = :skillId")
    public List<Craftsman> getCraftsmanBySkill(@Param("skillId") Long skillId);

以下是在MySql中有效的查询: 这让所有拥有id 1技能的工匠都得到了:

select c.name from craftsman c, craftman_skill cs 
where cs.craftman_id = c.id 
and cs.skill_id = 1;

以下是我得到的错误:

Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: skill_id of: com.craftsmen.crafts.persistence.Skill [SELECT c FROM com.craftsmen.crafts.persistence.Craftsman c JOIN c.skillList sl WHERE c.skillList.skill_id = :skillId ]
Caused by: org.hibernate.QueryException: could not resolve property: skill_id of: com.craftsmen.crafts.persistence.Skill [SELECT c FROM com.craftsmen.crafts.persistence.Craftsman c JOIN c.skillList sl WHERE c.skillList.skill_id = :skillId ]

2 个答案:

答案 0 :(得分:2)

我想问题是,您的Skill实体确实没有skill_id,或者更好,id

您是否曾尝试向Skill实体提供id

@Entity
@Table(name = "skill")
public class Skill {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

   @ManyToMany(mappedBy = "skillList")
   @JsonBackReference
   private List<Craftsman> craftmanList;
}

在您的Craftsman实体

中引用它
@Entity
@Table(name = "craftsman")
public class Craftsman {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToMany
    @JoinTable(name = "craftman_skill", joinColumns = @JoinColumn(name = "craftman_id", referencedColumnName = "id"), 
        inverseJoinColumns = @JoinColumn(name = "skill_id", referencedColumnName = "id"))
    private List<Skill> skillList;
}

然后将Query更改为

SELECT c FROM Craftsman c JOIN c.skillList sl WHERE sl.id = :skillId

这应该可以解决问题。

答案 1 :(得分:0)

此外,您可以考虑在此处使用JpaRepository的选项:

public interface CraftsmanRepository extends JpaRepository<Craftsman, String> {
    public List<Craftsman> getBySkillListIn(@NotEmpty List<Skill> skillList);

}

这意味着,Jpa,通过写入方法名称已经将查询映射到您的SQL查询(如果没有,请尝试)

在方法结束时,“在”意味着它应该检查不是一个值而是多个值

在SQL In中也可以工作并执行以下操作:

where <condition> And <>condition And <condition> And...