5

Is there a way with hibernate to define default values for each field and for the sake of database size write null instead of these default values?

For inst. let's say the default value for String is "". I would like Hibernate to:

  1. return "" for each field, that has NULL in database.
  2. write NULL to database, when I try to write ""

Of course, I can write thousands of Getters and Setters, but can it be done automatically?

Vojtěch
  • 11,312
  • 31
  • 103
  • 173
  • possible duplicate of [How to set default value in Hibernate](http://stackoverflow.com/questions/3110266/how-to-set-default-value-in-hibernate) – Jason C Mar 06 '14 at 09:29

2 Answers2

6

If you want a real database default value, use columnDefinition - @Column(name = “myColumn”, nullable = false, columnDefinition = “int default 100"). Notice that the string in columnDefinition is database dependent. Also if you choose this option, you have to use dynamic-insert, so Hibernate doesn't include columns with null values on insert. Otherwise talking about default is irrelevant.

But if you don't want database default value, but simply a default value in your Java code, just initialize your variable like that - private Integer myColumn = 100;

Source:

How to set default value in Hibernate

Of course, instead of using:

columnDefinition = “int default 100"

Try something like:

columnDefinition = “TEXT default `default_text`"

I'm not sure if that's syntaically correct, but check these out:

Text Field using Hibernate Annotation

Set default values using hibernate annotations in MYSQL

Community
  • 1
  • 1
  • When you declare the attributes of your class, you can initialize your default values of respective attributes there. That should work. – Mukesh S Jul 26 '13 at 14:19
  • 1
    Thanks for your answer, but it does not answer my question - I don't want to store the default values in the database, I want to store NULL, whenever the default value is involved. As I wrote: `I would like Hibernate to write NULL to database whenever I try to write ""`. – Vojtěch Jul 26 '13 at 18:00
  • 1
    Have you tried using a validator? Check this out: http://blog.inflinx.com/2012/04/24/custom-jsr-303-constraints/ – But I'm Not A Wrapper Class Jul 26 '13 at 18:18
0

You may implement such thing using field getters, Its simple and will serve the purpose.

varun
  • 684
  • 1
  • 11
  • 30