Avoid insert 'null' values to database table via JPA

扶醉桌前 提交于 2019-12-04 15:59:55

问题


im starting with JPA2 and feel quite comfortbale so far. But I have a problem when persisting Entities with null property values for NON NULL database fields with default value.

I would like to be able to leave the entity property null and let the database insert the default value.

My current setup is openJPA with PostgreSQL.

I have this VERSION database table (Vorgabewert = Default value):


     Spalte     |             Typ             |         Attribute
----------------+-----------------------------+----------------------------
 status_        | smallint                    | not null Vorgabewert 0
 time_          | timestamp without time zone | not null
 system_time    | timestamp without time zone | not null Vorgabewert now()
 version        | character varying(20)       | not null
 activationtime | timestamp without time zone |
 importtime     | timestamp without time zone |

I have an entity (Java DTO) which maps the database fields (except 'status') by xml configuration.

I hoped I could insert an entity without the system_time set and expected that the database will fill the current time as default value.

JPA constructs the following SQL-Query:

INSERT INTO public.version (version, activationtime, importtime, system_time, time_) VALUES (?, ?, ?, ?, ?) [params=?, ?, ?, ?, ?]

and Postgres reacts with:

FEHLER: NULL-Wert in Spalte »system_time« verletzt Not-Null-Constraint (sorry for German language but this message means the Not-Null-Constraint violation on 'system_time').

So what can I do? Is this a JPA or Database Problem. Can I configure JPA to exclude null properties from the INSERT SQL Statement.

I want to have the ability to set the 'system_time' in my entity or to let it be 'null' and let the database put the default value.

Any help is welcome!

Regads Klaus


回答1:


I would not rely on default values in the database in conjunction with JPA. You would have to read the entity back after the insert otherwise you have a mismatch between the entity state and the db state.

Choose the pragmatic approach here and initialise all values in java. Never heard of a way to tell JPA/Hibernate to leave out null values in an insert/update.




回答2:


Using the annotation

@Column(insertable = false)

will prevent the value being generated in the sql.




回答3:


In the Annotation @Column put the atribute insertable to false like this:

`@Column(name="system_time", insertable = false)`

Or if you need check when the value is NULL then make a Trigger BEFORE INSERT on the table.




回答4:


From documentation : columnDefinition : The SQL fragment that is used when generating the DDL for the column.

By using columnDefinition, you can specify constraints as required.

   @Column(name="COLUMN_NAME", 
   columnDefinition="DATE DEFAULT CURRENT_DATE",table="TABLE_NAME")

Else you can try to initialize field in entity itself to get rid of this.

    @Column(name = "somedate", nullable = false)
    private Date someDate = new Date();

So by default current date will be inserted if you do not set it.




回答5:


I found out a simple solution: define a default value in the pojo.

@Column(name="system_time")
private Date systemTime = new Date();



回答6:


I use this (against an Oracle database):

@Temporal(TemporalType.TIMESTAMP)
@Column(name="CREATION_TIME", 
        columnDefinition="TIMESTAMP DEFAULT SYSTIMESTAMP",
        nullable=false,
        insertable=false,
        updatable=false)
private Date creationTime;



回答7:


you can avoid the null property by add nullable=false to the @column annotation. like this

@Column(name = "muColumn", nullable = false)

how to avoid the null property in insert or update




回答8:


To exclude null property values in the hibernate insert sql stmt use attribute dynamic-insert=true.

1.@org.hibernate.annotations.Entity(dynamicInsert = true) add this on the class 2.In xml mapping , use dynamic-insert=true attribute in class tag.




回答9:


Simply leave out the system_time from the columns in the INSERT statement.




回答10:


I don't know of any way to do this in JPA.

But you could add a trigger to the database which catches attempts to insert NULL into the column in question, and rewrites the insert to insert the default? Essentially, you move the default-generation behaviour entirely down into the database, rather than splitting it between JPA and the database.

However, as bert points out in his answer, this would leave the object and the database inconsistent, which is almost certainly a bad think.




回答11:


you can use this way:

@JoinColumn(name = "team_id", nullable = false)

Using this way, JPA will check NULL value.



来源:https://stackoverflow.com/questions/4508622/avoid-insert-null-values-to-database-table-via-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!