0

Is there a way to set a default value for existing entries after the column has been created using Hibernate?

Found that the operation could be done manually by:

ALTER TABLE Employee 
ADD DEFAULT('SANDNES') FOR CityBorn

but is there a way to do something using hibernate?

Draaksward
  • 759
  • 7
  • 32

2 Answers2

0

That would be the way in hibernate.

@Column(name="CityBorn", columnDefinition="default 'SANDNESS'")
private String cityBorn;
erolkaya84
  • 1,769
  • 21
  • 28
0

You can either use the annotation

@ColumnDefault("SANDNES")

like specified here

or the xml-fragment

  <column name="CityBorn" default="SANDNES" />

like specified here

If you want to let Hibernate re-create your databse, you have to specify hibernate.hbm2ddl.auto=update, but this is not the recommended way for production (see for example this question) Normally one would use a third-party tool for schema-migration (e.g liquibase or flyway). The possibilities of hbm2ddl (used by Hibernate) are limited.

Community
  • 1
  • 1
Andreas Aumayr
  • 1,006
  • 1
  • 11
  • 17
  • Thanks for the reply. Tried this way. Works only on new entries. The idea is to set a default value of a column to the existing values in the db. – Draaksward Apr 24 '16 at 11:31
  • You mean updare all records within the db, or setting the (java) field of the entity to a default value if the column is empty? – Andreas Aumayr Apr 24 '16 at 11:50
  • Just realized what i was hoping to achieve with the "update existing entries" :) Yea, the idea was to update all of the records(or this could be done from the entity declaration?) – Draaksward Apr 24 '16 at 11:59