我有一个静态类,如:

public class Sex{

private final int code;
private final String status;

public static final int TOTAL = 3;

private Sex(int c, String s) {
code = c;
status = s;
}

public static final Sex UNDEFINED = new Sex(1, "UNDEFINED");
public static final Sex MALE = new Sex(2, "MALE");
public static final Sex FEMALE = new Sex(3, "FEMALE");
private static final Sex[] list = { UNDEFINED, MALE, FEMALE };

public int getCode() {
return code;
}

public String getStatus() {
return status;
}

public static Sex fromInt(int c) {
if (c < 1 || c > TOTAL)
throw new RuntimeException("Unknown code for fromInt in Sex");
return list[c-1];
}

public static List getSexList() {
return Arrays.asList(list);
}
}


而且,我有一个实体类

@Entity
@Table(name="person")

public class Person{

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;// setter/getter omitted

    private Sex sex;
    public final Sex getSex() {
    return this.sex;
    }
    public final void setSex(final Sex argSex) {
    this.sex = argSex;
    }
}


我想在个人表的数据库中保存sex_id。但是setter / getter应该是指定的,因为我要将代码写为-

Person person = new Person();
person.setSex(Sex.MALE);
Dao.savePerson(person);


如何用JPA注释Sex

最佳答案

由于您不想在数据库中创建新的Sex实例,为什么不对enum使用class而不是Sex

如果这样做,您只需在Sex类中用@Enumerated(EnumType.STRING)注释Person属性。完整示例here(或仅使用Google,您会发现很多)

关于java - 在JPA( hibernate )中保存非持久对象ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8412605/

10-10 17:02