How to set a default entity property value with Hibernate

后端 未结 17 2315
一整个雨季
一整个雨季 2020-11-28 02:53

How do I set a default value in Hibernate field?

17条回答
  •  离开以前
    2020-11-28 03:01

    Suppose we have an entity which contains a sub-entity.

    Using insertable = false, updatable = false on the entity prevents the entity from creating new sub-entities and preceding the default DBMS value. But the problem with this is that we are obliged to always use the default value or if we need the entity to contain another sub-entity that is not the default, we must try to change these annotations at runtime to insertable = true, updatable = true, so it doesn't seem like a good path.

    Inside the sub-entity if it makes more sense to use in all the columns insertable = false, updatable = false so that no more sub-entities are created regardless of the method we use (with @DynamicInsert it would not be necessary)

    Inserting a default value can be done in various ways such as Default entity property value using constructor or setter. Other ways like using JPA with columnDefinition have the drawback that they insert a null by default and the default value of the DBMS does not precede.


    Insert default value using DBMS and optional using Hibernate

    But using @DynamicInsert we avoid sending a null to the db when we want to insert a sub-entity with its default value, and in turn we allow sub-entities with values other than the default to be inserted.

    For inserting, should this entity use dynamic sql generation where only non-null columns get referenced in the prepared sql statement?

    Given the following needs:

    • The entity does not have the responsibility of creating new sub-entities.
    • When inserting an entity, the sub-entity is the one that was defined as default in the DBMS.
    • Possibility of creating an entity with a sub-entity which has a UUID other than the default.

    DBMS: PostgreSQL | Language: Kotlin

    @Entity
    @Table(name = "entity")
    @DynamicInsert
    data class EntityTest(
            @Id @GeneratedValue @Column(name = "entity_uuid") val entityUUID: UUID? = null,
    
            @OneToOne(cascade = [CascadeType.ALL])
            @JoinColumn(name = "subentity_uuid", referencedColumnName = "subentity_uuid")
            var subentityTest: SubentityTest? = null
    ) {}
    
    @Entity
    @Table(name = "subentity")
    data class SubentityTest(
            @Id @GeneratedValue @Column(name = "subentity_uuid", insertable = false, updatable = false) var subentityUUID: UUID? = null,
            @Column(insertable = false, updatable = false) var name: String,
    ) {
            constructor() : this(name = "")
    }
    

    And the value is set by default in the database:

    alter table entity alter column subentity_uuid set default 'd87ee95b-06f1-52ab-83ed-5d882ae400e6'::uuid;
    

    GL

    • Source 1
    • Source 2

提交回复
热议问题