简体   繁体   中英

Hibernate/JPA: storing constants in entity class?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM