涉及foreign_key的JPA自定义查询

时间:2015-03-10 17:46:23

标签: java jpa

我想创建一个JPA查询来计算具有特定外键的记录数。

实体:

@Entity(name = "person")
@Inheritance(strategy = InheritanceType.JOINED)
public class Person {

  @Id
  private Long id;
  private String firstName;
  private String lastName;
  private String phoneNumber;
  @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
  @JoinColumn(name = "ADRESS_FK")
  private ADDRESS address;
}


@Entity(name = "address")
public class Address {

  @Id
  private Long id;
  private String country;
  private String city;
  private String street;
  private String number;
}

这就是我正在尝试的,这在JPA中看起来怎么样?

public Long getOccurences( Long id ) {
  Query query = _entityManager.createQuery( "Select count(*) from Persons p where p.address = ?1" );
  query.setParameter( 1, id );
  return query.getSingleResult() );

}

0 个答案:

没有答案