我创建了两个表:Project和Resource。实体类如下:
@Entity
@Table(name="project")
public class Project {
@Id
private int projectId;
private String name;
private String createdBy;
.
.
.
}
@Entity
@Table(name="resource")
public class Resource {
@Id
private int resourceId;
private String name;
private String createdBy;
private Set<Project> projects;
@JoinTable(name="project_resources",joinColumns={@JoinColumn(name="project_id")},
inverseJoinColumns={@JoinColumn(name="resource_id")})
public Set<Project> getProjects() {
return projects;
}
public void setProjects(Set<Project> projects) {
this.projects = projects;
}
.
.
}
一些数据库值:
resource_id, project_id
r-123-abcop, p-qweer033
r-153-adetr, p-qweer033
r-460-uerty, p-qweer033
r-087-xcvbx, p-qweer033
r-askf-44uj, p-euyru85r
r-6yhe-hefn, p-euyru85r
r-er7u-ufgm, p-euyru85r
r-ehw8i-nfm, p-euyru85r
(表project_resources没有实体类,Project表将不具有Resource表依赖关系,但是Resource将具有Project的依赖关系,如您从类中看到的那样)
现在,如果要获取项目中存在哪些资源,那么我必须首先获取所有资源,然后根据项目ID筛选资源。但是,如果我能够查询此project_resources表,我将能够轻松获得这些值。
我想生成类似的查询
select * from project_resources where project_id = '';
如何让休眠类理解选择此project_resources表?还是任何更好的解决方案,如何基于projectId获取资源?
答案 0 :(得分:0)
您不需要创建表project_resources
。借助JPA多对多映射,您可以在project
类中使用查询。它会自动映射到资源。您可以引用链接https://www.baeldung.com/jpa-many-to-many
答案 1 :(得分:0)
尝试使用此命名查询
@NamedQuery(
name = "getResourcesByProjectid",
query =select r from Resource r left join r.projects p where p.projectId = ?1
)