Reputation: 43
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);
Upvotes: 3
Views: 3720
Reputation: 42114
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.
Upvotes: 3