使用注释的 Hibernate Enum 映射
我有一个现有数据库,现在正在使用 hibernate 连接到该数据库。我目前无法更改其中的数据,也无法让所有内容都在单个列之外运行。
我有一个状态列,其值是:
- new
- mailed
- in
- out
并且该列映射如下:
@Column(name = "STATUS", nullable = false, length = 50)
@Enumerated(EnumType.STRING)
private TeamMemberStatus status;
我真的很想(出于应用程序原因)将此列映射为 Java 枚举(TeamMemberStatus),但是由于事实上,“new”是 Java 中的关键字,我不能将其作为枚举成员。
如果我有枚举常量 NEW、MAILED、IN 和 OUT 休眠会失败,因为在 EnumType 内部它会执行 Enum.valueOf()。
有什么方法可以让我将其映射到我的枚举,而不必编写复杂的用户类型?
-- 添加内容
My Enum 如下:
public enum TeamMemberStatus {
NEW, MAILED, IN, OUT
}
是一个有效的 Java 枚举,但与数据库的大小写不匹配。如果我更改它以匹配数据库,例如:
public enum TeamMemberStatus {
new, mailed, in, out
}
它将不会编译,因为“new”是 Java 保留字。
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:
- new
- mailed
- in
- out
And the column is mapped as follows:
@Column(name = "STATUS", nullable = false, length = 50)
@Enumerated(EnumType.STRING)
private TeamMemberStatus status;
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.
If I have the enum contstants NEW, MAILED, IN and OUT hibernate fails as inside EnumType it does a Enum.valueOf().
Is there any way for me to map this to my Enum without having to write a complex UserType?
-- added content
My Enum like this:
public enum TeamMemberStatus {
NEW, MAILED, IN, OUT
}
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
}
It won't compile as 'new' is a Java reserved word.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您可以在数据库中使用 SQL UPPER 语句,则无需使用任何 UserType
UPDATE 即可工作UPDATE
好吧,它可能不是最好的解决方案,但它可以解决您想要的问题
}
If you can use a SQL UPPER statement at database, It will work without using any UserType
UPDATE
Well, It can not be The nicest solution but it solves what you want
}
如果您的数据库值为“new”、“mailed”、“in”和“out”,那么您的枚举需要完全相同的名称。 - 我认为问题是,您的枚举是大写字母,但您的数据库值不是。
If your Database values are "new", "mailed", "in" and "out" then your Enum need exactly the same names. - I believe that the problem is, that your Enums are in capital letters but your data base values not.