Hibernate/JPA: storing constants in entity class?

↘锁芯ラ 提交于 2019-12-12 14:27:31

问题


I work on remote project and found interesting record in log:

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

with logging set to:

<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.

When I have seen Bail.java source I am surprised:

String[] monthName = {"Января", "Февраля",
        "Марта", "Апреля", "Мая", "Июня", "Июля",
        "Августа", "Сентября", "Октября", "Ноября",
        "Декабря"
};

So this is constant field!

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?

I think that static keyword do the job and I think about refactoring code to:

public static final String[] monthName = 
    Collections.unmodifiableList(Arrays.asList(
        "Января", "Февраля", "Марта", "Апреля", "Мая", "Июня", "Июля",
        "Августа", "Сентября", "Октября", "Ноября", "Декабря"
));

Because production version deployed with hbm2ddl.auto=update I think I should warn DBA to remove unnecessary monthName column.


回答1:


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:

  • 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.


来源:https://stackoverflow.com/questions/34467121/hibernate-jpa-storing-constants-in-entity-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!