2011-12-07 79 views
0

我有一个静态类,如:保存非持久对象ID

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在数据库在人员表中。但二传手/吸气应符合规定,因为我想我写代码 -

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

如何使用JPA注释Sex

回答

4

由于您不想在数据库中创建新的Sex实例,因此您为什么不使用enum而不是来代替Sex

如果你这样做,你只需要在Person类中注释Sex属性@Enumerated(EnumType.STRING)。完整的例子here(或只是谷歌它,你会发现很多)

1

为什么不使用枚举器性别,然后使用@Enumerated而不是?

@Enumerated(EnumType.STRING) 
    Sex sex