使用注释的休眠枚举映射 [英] Hibernate Enum mapping using annotaions
问题描述
我有一个现有的数据库,我现在正在使用休眠连接到该数据库.我目前无法更改其中的数据,并且除了单个列之外,其他所有内容都可以正常工作.
I have an existing database that I am now connecting to using hibernate. I cannot change the data in it at the moment and have everything working apart from a single column.
我有一个包含值的状态列:
I have a status column that has the values:
- 新
- 邮寄
- 在
- 出
并且列映射如下:
@Column(name = "STATUS", nullable = false, length = 50)
@Enumerated(EnumType.STRING)
private TeamMemberStatus status;
我真的很想(出于应用程序的原因)将此列映射为 Java 枚举(TeamMemberStatus),但由于new"是 Java 中的关键字这一事实我不能这样做作为枚举成员.
I would REALLY like (for application reasons) to have this column mapped as a Java Enum (TeamMemberStatus), but due to the fact that 'new' is a keyword in Java I cannot have that as an enum member.
如果我有枚举常量 NEW、MAILED、IN 和 OUT 休眠失败,因为在 EnumType 内部它会执行 Enum.valueOf().
If I have the enum contstants NEW, MAILED, IN and OUT hibernate fails as inside EnumType it does a Enum.valueOf().
有什么方法可以让我将它映射到我的 Enum 而不必编写复杂的 UserType?
Is there any way for me to map this to my Enum without having to write a complex UserType?
-- 添加内容
我的枚举是这样的:
public enum TeamMemberStatus {
NEW, MAILED, IN, OUT
}
是有效的 Java 枚举,但与数据库的大小写不匹配.如果我将其更改为匹配数据库,例如:
is a valid Java enum, but not matching the case of the database. If I change it to match the database like:
public enum TeamMemberStatus {
new, mailed, in, out
}
它不会编译,因为new"是 Java 保留字.
It won't compile as 'new' is a Java reserved word.
推荐答案
如果你可以在数据库中使用 SQL UPPER 语句,它会在不使用任何 UserType 的情况下工作
If you can use a SQL UPPER statement at database, It will work without using any UserType
更新
好吧,它不可能是最好的解决方案,但它可以解决您想要的
Well, It can not be The nicest solution but it solves what you want
@Entity
public class WrapperEntity {
private TeamMemberStatus memberStatus;
@Transient
private TeamMemberStatus getMemberStatus() {
return this.memberStatus;
}
public void setMemberStatus(TeamMemberStatus memberStatus) {
this.memberStatus = memberStatus;
}
@Column(name="STATUS", nullable=false, length=50)
public String getMemberStatusAsString() {
return memberStatus.name().toLowerCase();
}
public void setMemberStatusAsString(String memberStatus) {
this.setsetMemberStatus(TeamMemberStatus.valueOf(memberStatus.toUpperCase()));
}
}
这篇关于使用注释的休眠枚举映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!