查询具有ManyToMany关系条件的实体

时间:2013-06-09 11:32:03

标签: jpa jpa-2.0

我有两个Entites

    @Entity 
    public Report() 

@Id
@Column(name = "REPORT_ID")
private long id;

@JsonIgnore
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
      name="reports_projects",
      joinColumns={@JoinColumn(name="report_id", referencedColumnName="REPORT_ID")},
      inverseJoinColumns={@JoinColumn(name="project", referencedColumnName="PROJECT_ID")})
private List<Project> projects; 

第二是:

    @Entity(name = "projects")
    public class Project 

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "PROJECT_ID")
// seems like spring's jpa has issue hanlde "_" between the words
private long id;

@Column(name = "CODE", nullable = false)
private String code;

@Column(name = "DESCRIPTION", nullable = false)
private String description;

@Column(name = "CREATION_DATE", nullable = false)
private Date creationDate;

我想通过projects.code查询报告 尝试了一些像

这样的东西
    @Query("select reports from org.jpp.domain.quicksearch.ReportQS reports inner join   reports.projects p  where p.code in :code")

并且

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<QuickSearchResult> query = cb.createQuery(QuickSearchResult.class);
Metamodel m = em.getMetamodel();

EntityType<ReportQS> ReportQSMetaModel = m.entity(ReportQS.class);

Root<ReportQS> reportsQS = query.from(ReportQS.class);
Root<Project> projects = query.from(Project.class);
Join<ReportQS, Project> joinReportsProjects =  reportsQS.join("projects");
Predicate condition = cb.equal(projects.get("code"),"gnrl");
query.select(reportsQS).where(condition);

TypedQuery<QuickSearchResult> q = em.createQuery(query);

我得到两个查询的空结果 知道如何让这个工作吗?

提前致谢, 橡木

1 个答案:

答案 0 :(得分:1)

请尝试以下代码:

String query = "select r from ReportQS r join r.projects p where p.code = :code";
List<ReportQS> reports = em.createQuery(query,ReportQS.class).setParameter("code","grnl").getResultList();

确保ReportQS是实体类的名称(在示例代码中,您具有不同的类名和查询中使用的不同实体名称。)