java hibernate 覆盖枚举/字符串映射值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16045561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java hibernate override enum/string mapping values
提问by ducin
I've got a following Hibernate model:
我有以下 Hibernate 模型:
@Entity
@Table(name = "category")
public class Category {
@Enumerated(EnumType.STRING)
@Column(name = "type")
private CategoryType type;
This is the enumeration referenced by hibernate:
这是hibernate引用的枚举:
public enum CategoryType {
INCOME, OUTCOME;
}
THe corresponding database field is a varchar which takes 2 possible values: "CategoryIncome" and "CategoryOutcome".
相应的数据库字段是一个 varchar,它采用 2 个可能的值:“CategoryIncome”和“CategoryOutcome”。
This method actually calls hibernate:
这个方法实际上调用了hibernate:
public List<Category> findAllByType(CategoryType type) {
session = sessionFactory.openSession();
tx = session.beginTransaction();
Query query = session.createQuery(
"FROM Category WHERE type = :type");
query.setParameter("type", type);
List list = query.list();
tx.commit();
session.close();
return list;
}
I managed to get my code work (I mean it compiles), but it works badly - it executes following SQL query:
我设法让我的代码工作(我的意思是它可以编译),但效果不佳 - 它执行以下 SQL 查询:
WHERE type = "INCOME"
whereas I would like it to be:
而我希望它是:
WHERE type = "CategoryIncome"
How can I map enum values into string values for hibernate? I know that EnumType.STRING
tells hibernate to cast the enum values to string (could be EnumType.ORDINAL to cast it to integers). But how can I override the default enum-string mapping?
如何将枚举值映射到休眠的字符串值?我知道这EnumType.STRING
告诉 hibernate 将枚举值转换为字符串(可以是 EnumType.ORDINAL 将其转换为整数)。但是如何覆盖默认的枚举字符串映射?
回答by Ashish Thukral
You will have to use your customized usertype for Hibernate persistance, Hibernate uses name()
function of enum
to get string representation, not toString()
.
您必须使用自定义的用户类型来实现 Hibernate 持久性,Hibernate 使用name()
ofenum
来获取字符串表示,而不是toString()
.
See this Hibernate @Enumerated mapping