我正在使用具有两个类的 JPA 模型。第一个是用“动态”数据映射表,第二个是用只读引用数据映射表。
例如,我有一个Person
实体映射一个人表,其中包含对该实体的@OneToOne 引用,该Civility
实体本身映射到其中只有 3 条记录(小姐、夫人和先生)的文明表(2 列)。
我想知道基于文明值对人员实体编写查询的最佳方式。例如,我将使用什么查询来获取所有具有礼貌 = 先生的人?
谢谢。
映射参考查找数据的一种方法是在 jpa 中使用 @Enumerated 注释。您仍然必须使用查找值创建枚举,但这就是它无论如何都是参考数据的原因。
例如,我有一个评级代码,它是表上的字符串/varchar 值。但是可以使用枚举来使用它:
@Enumerated(EnumType.STRING)
@Column
public RatingCode getRating() {
return rating;
}
public void setRating(RatingCode rating) {
this.rating = rating;
}
枚举是:
public enum RatingCode {
Core, Star
}
使用单元测试来尝试所有值,并且您知道这是获取参考数据的安全方法。
您仍然可以使用 HQL 提取值,并将枚举作为值传递:
hql = "select r from Rating as r where r.rating = :aEnum"
// and in the call to pass the parameter
qry.setParameter("aEnum", aRatingCode)
枚举是 Rating 实体中的一个字段:
@Entity
@Table
public class Rating {
private Integer rating_Id;
private RatingCode rating;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column
public Integer getRating_Id() {
return rating_Id;
}
public void setRating_Id(Integer rating_Id) {
this.rating_Id = rating_Id;
}
@Enumerated(EnumType.STRING)
@Column
public RatingCode getRating() {
return rating;
}
public void setRating(RatingCode rating) {
this.rating = rating;
}
}
所以我有一个需要评级的个人资料,所以我通过枚举查找评级并将其添加到个人资料中。
Profile p = new Profile();
RatingServiceI rs = new RatingService()
Rating r = rs.getRating(RatingCode.Core);
p.setRating(r);
您没有发布实体定义,因此您需要解释此答案中的代码以匹配您的实际模型。另外,请注意,在这种情况下,查询实体本身与基础表中的数据是否为“只读”无关:
final String queryStr = "SELECT p FROM Person p WHERE p.civility.value = :value";
final TypedQuery<Person> query = entityManager.createQuery(queryStr, Person.class);
query.setParameter("value", "Mr");
List<Person> results = query.getResultList();