gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:11:11 33 4
gpt4 key购买 nike

我有 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 ]

最佳答案

我猜问题是,您的 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;
}

然后将查询更改为

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

这应该可以解决问题。

关于java - 如何在多对多关联表上编写查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50056098/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com