Hibernate / JPA:在实体类中存储常量? [英] Hibernate/JPA: storing constants in entity class?
问题描述
I work on remote project and found interesting record in log:
我在远程项目上工作并在日志中找到有趣的记录: org.hibernate.tool.hbm2ddl.SchemaUpdate
在org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:251)上的调用者+ 0
=> alter table bail添加列monthName tinyblob
2015-12-26 00:28:30,835 DEBUG org.hibernate.tool.hbm2ddl.SchemaUpdate
Caller+0 at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:251)
=> alter table bail add column monthName tinyblob
将日志记录设置为:
<logger level="trace" name="org.hibernate.tool.hbm2ddl"/>
在尝试识别发生什么时:
when try to identify what happen to:
<prop key="hibernate.hbm2ddl.auto">update</prop>
从备份开始第一次运行。
on first run from backup.
String[] monthName = {"Января", "Февраля",
"Марта", "Апреля", "Мая", "Июня", "Июля",
"Августа", "Сентября", "Октября", "Ноября",
"Декабря"
};
所以这是不变的字段!
在JPA / Hibernate方面存储实体类中的常量声明是正确的吗?
Is it right to store constants declaration in entity class in term of JPA / Hibernate?
我应该如何标记常量,使其不是实体属性?
How should I mark constant so it wouldn't be entity property?
我认为 static
关键字可以完成这项工作,并且我考虑将代码重构为:
I think that static
keyword do the job and I think about refactoring code to:
public static final String[] monthName =
Collections.unmodifiableList(Arrays.asList(
"Января", "Февраля", "Марта", "Апреля", "Мая", "Июня", "Июля",
"Августа", "Сентября", "Октября", "Ноября", "Декабря"
));
因为使用 hbm2ddl.auto = update
我认为我应该警告DBA删除不必要的 monthName
列。
Because production version deployed with hbm2ddl.auto=update
I think I should warn DBA to remove unnecessary monthName
column.
推荐答案
默认情况下,所有属性都会被持久保存,就好像它们被标记为 @Basic
注释。
All properties are persisted by default as if they were marked with the @Basic
annotation.
为了避免字段被持久存在,您有以下选项:
To avoid a field from being persisted you have the following options:
- 您可以使用
@Transient
- 你可以使它成为
static final
字段,但是您可能希望将其移至常量类实用程序中 - 最好的方法是使用Java 8
java.time.Month
,然后国际化月份名称,以便您可以支持多种语言用户界面,同时在数据库中存储通用名称。
- you can mark it with
@Transient
- you can make it a
static final
field, but then you might want to move it to a constants class utilities anyway - the best approach is to use the Java 8
java.time.Month
and then internationalize the month name so you can support multiple languages in the UI, while storing a universal name in the DB.
这篇关于Hibernate / JPA:在实体类中存储常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!