Default value in HIBERNATE Database independently

How to initialize Field in Hibernate @Entity without using @Column( columnDefenition=”” ) ?
WHY?
Because columnDefinition is DB dependently option.

Imagine you have some @Entity :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    @Column( name = "insstmp", nullable = false )
    @Type( type = "org.joda.time.contrib.hibernate.PersistentDateTime" )
    private DateTime insstmp;// date without time

    @Column( name = "updstmp", nullable = false )
    @Type( type = "org.joda.time.contrib.hibernate.PersistentDateTime" )
    private DateTime updstmp;// date without time

    /**
     * We set default value in case if the value is not set yet.
     */

    @PrePersist
    public void prePersist() {

        if ( this.updstmp == null ) {
            // Default value
            this.updstmp = getUpdstmp();
        }
        if ( this.insstmp == null ) {
            // Default value
            this.insstmp = getInsstmp();
        }
    }


    /**
     * Getter.
     *
     * @return the insstmp
     */

    public final DateTime getInsstmp() {

        return insstmp == null ? new DateTime( DateTimeZone.UTC ) : insstmp;
    }

    /**
     * Getter.
     *
     * @return the updstmp
     */

    public final DateTime getUpdstmp() {

        return updstmp == null ? new DateTime( DateTimeZone.UTC ) : updstmp;
    }
Tagged , , . Bookmark the permalink.

Leave a Reply