如何使用JPA和Hibernate在应用程序中创建查找表?

时间:2019-04-23 19:39:33

标签: java hibernate jpa

我有一个使用JPA和Hibernate的应用程序。我有一个名为Person的实体,该实体具有要用于查找表的多个字段。例如,有一种性别,[我认为]应该看起来像这样:

@Entity
@Table(name = "genderLookup")
@EntityListeners(AuditingEntityListener.class)
public class GenderLookup extends Auditable<String> implements Serializable {

    @Id
    private Long id;

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

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

    // Default empty public constructor
    public GenderLookup() {
    }

    public String getGenderName() {
        return genderName;
    }

    public void setGenderName(String genderName) {
        this.genderName = genderName;
    }

    public String getGenderCode() {
        return genderCode;
    }

    public void setGenderCode(String genderCode) {
        this.genderCode = genderCode;
    }

}

要涵盖这些性别:

// "Gender","Code"
// "Male","M"
// "Male Impersonator","G"
// "Female","F"
// "Female Impersonator","N"
// "Unknown","X"
// "Male Name, No Gender Given","Y"
// "Female Name, No gender Given","Z"

这是我当前的Person实体:

@Entity
@Table(name = "person")
@EntityListeners(AuditingEntityListener.class)
public class Person extends Auditable<String> implements Serializable
{
    @Column(name = "gender", nullable = false);
    private String gender;

    public Person(){
    }

    public Person(Object object){
        this.gender = object.getGender();
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

当前,如您所见,性别被传递到构造函数中的Person中,并以此方式进行设置。就像我说的那样,我宁愿使用查找表,但是我很少有JPA经验,也不知道我在做什么。

我在Person实体中尝试过此操作:

@OneToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "genderCode", nullable = false, insertable = false, updatable = false)
private String gender;

但是没有用。

如何使它正常工作?

0 个答案:

没有答案