javaenumsopenjpa

how to use enum with jpa as a data member of persisted entity?


Please best practice and 'how to' for using enum with jpa as a data member of persisted entity. what is the best practice? I want to persist "C", "O" from enum. (codes). If this is not the correct approach please suggest.

Enum defination is --

public enum Status{
CLOSED ("C")
OPEN ("O")
private final int value;
private Status(final int pValue){
this.value = pValue;
}

public int value(){
 return this.value;
}

Solution

  • expected Solution: enum defination:

    public enum Status {
        CLOSED(1), NEW(2), RUNNING(3), OPEN(4), ADDED(5), SUCEESS(-1), DONE(0);
            private int code;
            private Status(int code) {
            this.code = code;
        }
            public int getCode() {
            return code;
        }
            public void setCode(int code) {
            this.code = code;
        }
            public static Status valueOf(int i){
            for (Status s : values()){
                if (s.code == i){
                    return s;
                }
            }
            throw new IllegalArgumentException("No matching constant for " + i);
        }
    

    }

    Entity Definition:

    @Entity
    @NamedQuery(name="Process.findAll", query="select p from Process p ")
    public class Process {
        
        @Id
        private long id;
        private String name;
        
        @Transient
        private transient Status status; //actual enum; not stored in db
            @Column(name="STATUS")  
        private int statusCode; // enum code gets stored in db
        
        @PrePersist
        void populateDBFields(){
            statusCode = status.getCode();
        }
        
        @PostLoad
        void populateTransientFields(){
            status = Status.valueOf(statusCode);
        }
        public long getId() {
            return id;
        }
        public void setId(long id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Status getStatus() {
            return status;
        }
        public void setStatus(Status status) {
            this.status = status;
        }
    }