java - JPA 最佳实践 - 加入只读数据

标签 java hibernate jpa join

我正在使用具有两个类的 JPA 模型。第一个是映射具有“动态”数据的表,第二个是映射具有只读引用数据的表。

作为示例,我有一个映射 Person 表的 Person 实体,其中包含对 Civility 实体的 @OneToOne 引用,该实体本身映射到 Civility 表(2 列),其中只有 3 条记录(Miss、Mrs 和 Mr)。

我想知道根据文明值编写对人员实体的查询的最佳方法。例如,我将使用什么查询来获取所有具有礼貌的人 = Mr?

谢谢。

最佳答案

映射引用查找数据的一种方法是在 jpa 中使用 @Enumerated 注释。您仍然必须使用查找值创建枚举,但这就是它无论如何都是引用数据的原因。

例如,我有一个评级代码,它是表上的 string/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)

枚举是评级实体中的一个字段:

@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);

关于java - JPA 最佳实践 - 加入只读数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10740787/

相关文章:

java - Android 设备和基于 Linux 的硬件之间的数据传输

java - 在*多线程* Swing 应用程序中使用 Hibernate 进行 session 管理

Java - 如何修正此算法,我不知道 value0 和 value1 何时不为空且为 null

java - Hibernate 中的外键共享

jakarta-ee - 通过集合集相等性选择实体

java - 如何使用java知道web容器的路径?

java - [错误]org.springframework.beans.factory.BeanCreationException

java - 在 hibernate 中仅插入子表

java - org.springframework.core.convert.ConverterNotFoundException : No converter found capable of converting from type Account to type AllAccount

java - hibernate 还是 'Do-It-Yourself"?