我有一个班级让员工说如下;
public class Employee{
... Other attributes ...
@Column @Enumerated(EnumType.Ordinal)
private Gender gender;
@Column @Enumerated(EnumType.Ordinal)
private EmployeeType employeeType;
... Getters & Setters ...
}
我的员工表是这样的。
Employee{
... other columns ....
gender int,
employeetype int,
...
}
我有一个通用的查找表查找
Lookups{
id long,
lookName String,
lookId int,
lookValue String
}
我希望通过hibernate将Genders和EmployeeTypes保存在Lookups表中,如下所示,我该怎么做;
+--+-------------+---------+------------+
|ID|LOOKUPNAME |LOOKUPID | LOOKUPVALUE|
+--+-------------+---------+------------+
+--+-------------+---------+------------+
|1 | GENDER | 1 | MALE |
+--+-------------+---------+------------+
|2 | GENDER | 2 | FEMALE |
+--+-------------+---------+------------+
|3 | EMPLOYEETYPE| 1 | TEAM MEMBER|
+--+-------------+---------+------------+
|4 | EMPLOYEETYPE| 2 | TEAM LEADER|
+--+-------------+---------+------------+
|5 | EMPLOYEETYPE| 3 | MANAGER |
+--+-------------+---------+------------+
答案 0 :(得分:0)
创建Lookups类。然后,对于Employee类的Gender和EmployeeType字段,将其替换为Lookups字段。然后删除Enumerated annotations。
答案 1 :(得分:0)
我的理解是,您希望仅以自动方式将所有常量/枚举存储在一个表中。
要做到这一点,你可以拥有
这样,启动类可以在启动时检查数据,如果不存在则插入它。
答案 2 :(得分:0)
也许你可以按照以下方式将它们放在一起并坚持下去?
import java.util.*;
enum Gender {
male, female
}
enum EmployeeType {
member, leader, manager
}
class Lookups {
public String toString() {
return id + " " + lookName + " " + lookId + " " + lookValue;
}
private Lookups(Enum e) {
id = ++n;
lookName = e.getClass().getName();
lookId = e.ordinal() + 1;
lookValue = e.name();
}
private static void create(Enum e) {
for (Object o : e.getDeclaringClass().getEnumConstants())
lookups.add(new Lookups((Enum) o));
}
final long id;
final String lookName;
final int lookId;
final String lookValue;
static long n;
static Set<Lookups> lookups = new LinkedHashSet<Lookups>();
static {
create(Gender.values()[0]);
create(EmployeeType.values()[0]);
}
}
public class Main {
public static void main(String[] args) {
for (Lookups lookups : Lookups.lookups)
System.out.println(lookups);
}
}