Spring数据jpa中的JPQL查询

时间:2015-07-08 21:36:41

标签: java spring jpa spring-data-jpa

让我们说:

class Range {
  public long start;
  public long end;
}

此JPA实体:

@Entity
@Table(name="entry")
public class Entry {
  @Id
  long id;

  @OneToMany
  Set<Individual> individuals;
}

另一个JPA实体:

@Entity
@Table(name="individual")
public class Individual {
  @Id
  long id;

  long code;

  @ManyToOne
  Entry entry;
}

和控制器:

public class IndexedEntryController {
  EntityManagerFactory emf;

  List<Entry> find(List<Range> lst) {
    String str = "";

    for(Range r:lst) {
      if(!str.isEmpty) {
        str += " or ";
      }
      str += "(i.code between " + r.start + " and " + r.end + ")";
    }

    String query = "Select i.entry from Individual i where " + str + " group by i.entry having count(i) > " + lst.size()-1;
    EntityManager em = emf.createEntityManager();

    return em.createQuery(query).getResultList();
  }
}

此查询返回n-1个人的所有条目,其中代码介于特定范围之一,其中n是范围数。

我想搬到春天JpaRepository。如何使用JpaRepository

实现此查询

0 个答案:

没有答案