0

i'm trying to set default value for column and i have tried with below code in entity

@Column(columnDefinition = "integer default 1")
private Integer views;

now after running server still i could see views as null in sql. Any idea why not able to save default value.

Application.yml

hibernate:
  ddl-auto: create

its always create as still its in development stage

SameerShaik
  • 488
  • 2
  • 10
  • 22
  • I guess, this would not update default values for existing records, but insert new records with this configuration given records are added via application. Or make sure that you have `property name="hibernate.hbm2ddl.auto" value="update"` set. – Ankur Jun 03 '20 at 08:57
  • Does this answer your question? [Setting default values for columns in JPA](https://stackoverflow.com/questions/197045/setting-default-values-for-columns-in-jpa) – Eklavya Jun 03 '20 at 13:40

2 Answers2

1

Please use the simple implementation in your code.

@Column("column name")
private Integer views = 1;

set Default value while create that variable. if you want to change view value by using setter method.

if your not set the value in the model means it take 1 as the default value.

Or if your want to use columnDefinition please use like follow

@Column(name="view",columnDefinition = "integer default '1'")
1

you mean you look at the already existing rows in the table and you expect them to have that value ?

if yes, then here is the problem.. you may need to run migration script to set the default value you want where its not set.

And for any future inserted rows I guess the default value should be set.

Z.yassine
  • 186
  • 1
  • 2
  • 10
  • No not the existing rows, its new development – SameerShaik Jun 03 '20 at 09:15
  • then, could you try just setting default value to the field like: private Integer views = 1, thats what basically the way i personally do it, you can also look at this here https://www.baeldung.com/jpa-default-column-values it explains the different ways to do it – Z.yassine Jun 03 '20 at 09:18
  • if that didn't work either, i wonder the way you add it ? do you have a DTO there that you convert and probably it sets the value to null and overrides it.. probably idk.. – Z.yassine Jun 03 '20 at 09:22
  • yeah i do have a DTO but initially view value will be null so entity has to take care of default values – SameerShaik Jun 03 '20 at 09:36
  • I see... do you have hibernate ddl update enabled, or its on prod / necessary to do the schema changes with migration scripts ? because in your case, you have to tell the DB itself to set the default values – Z.yassine Jun 03 '20 at 09:40