Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map Enums to a separate table with Hibernate?

I currently have a Hibernate mapping which works as follows:

Table 'TASK':
  id int, name varchar, status varchar

Enum

public enum TaskStatus {
  INVALID, INITIAL, IN_PROGRESS, PAUSED, DONE;
}

Type

@Entity
public class Task {

  @Column(name = "STATUS")
  @Enumerated(EnumType.STRING)
  private TaskStatus status;

  public TaskStatus getStatus() {
      return status;
  }

  public void setStatus(TaskStatus status) {
      this.status = status;
  }
}

I want to change this to save all possible status in one table such as:

Table 'TASK_STATUS':
  id int, status varchar

Table 'TASK':
  id int, name varchar, status_id int foreign key

Is it possible to define a mapping for the enum type using Hibernate Annotations and a way to map it to the Task Type. I still want the Java implementation to look like the one above (having the TaskStatus property instead of an int property) so i can comfortably use:

myTask.setStatus(TaskStatus.DONE);
like image 773
user1635452 Avatar asked Jan 21 '26 07:01

user1635452


1 Answers

Yes, if value set of status_id match to the ordinal of enum, simply use following:

@Column(name = "STATUS_ID")
@Enumerated(EnumType.ORDINAL )

Correct table structure (FK, TASK_STATUS table) will not be automatically generated by Hibernate.

If numerical values do not match to ordinal, then you have to create custom type. One example is given here, but you will of course use integer type instead of varchar.

like image 130
Mikko Maunu Avatar answered Jan 23 '26 19:01

Mikko Maunu