Mossaddeque Mahmood
Mossaddeque Mahmood

Reputation: 927

Save non-persistent object id in JPA (Hibernate)

I've a static class like:

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

And, I've an entity class

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

I want to save sex_id in database in person table. But setter/getter should be as specified, because I want write my code as -

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

How to annotate Sex with JPA?

Upvotes: 0

Views: 538

Answers (2)

Paul Dijou
Paul Dijou

Reputation: 76

Since you don't want to create new Sex instance in your database, why don't you use an enum instead of a class for Sex?

If you do so, you will just have to annotate you Sex attribute with @Enumerated(EnumType.STRING) in the Person class. Full example here (or just Google it and you will find plenty)

Upvotes: 4

danny.lesnik
danny.lesnik

Reputation: 18639

Why not to use enumerator Sex instead and then use @Enumerated instead?

 @Enumerated(EnumType.STRING)
   Sex sex

Upvotes: 1

Related Questions