Hibernate / JPA:将常量存储在实体类中吗?

gav*_*koa 3 java hibernate jpa constants hibernate-mapping

我从事远程项目,并在日志中找到了有趣的记录:

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
Run Code Online (Sandbox Code Playgroud)

日志设置为:

<logger level="trace" name="org.hibernate.tool.hbm2ddl"/>
Run Code Online (Sandbox Code Playgroud)

尝试确定会发生什么情况时:

<prop key="hibernate.hbm2ddl.auto">update</prop>
Run Code Online (Sandbox Code Playgroud)

第一次从备份运行。

当我看到Bail.java源代码时,我感到很惊讶:

String[] monthName = {"??????", "???????",
        "?????", "??????", "???", "????", "????",
        "???????", "????????", "???????", "??????",
        "???????"
};
Run Code Online (Sandbox Code Playgroud)

所以这是常数场!

用JPA / Hibernate将常量声明存储在实体类中是否正确?

我应该如何标记常量,使其不成为实体属性?

我认为该static关键字可以胜任工作,并且可以将代码重构为:

public static final String[] monthName = 
    Collections.unmodifiableList(Arrays.asList(
        "??????", "???????", "?????", "??????", "???", "????", "????",
        "???????", "????????", "???????", "??????", "???????"
));
Run Code Online (Sandbox Code Playgroud)

因为hbm2ddl.auto=update我部署了生产版本,所以我应该警告DBA删除不必要的monthName列。

Vla*_*cea 5

默认情况下,所有属性都将保留,就好像它们已被@Basic注释标记一样。

为避免保留字段,您可以使用以下选项:

  • 你可以用 @Transient
  • 您可以将其设置为static final字段,但是无论如何您可能想要将其移至常量类实用程序
  • 最好的方法是使用Java 8 java.time.Month,然后国际化月份名称,以便您可以在UI中支持多种语言,同时在数据库中存储通用名称。

  • 您可以使用static,然后Hibernate将不会保留这些字段。 (2认同)