views:

588

answers:

1

Hi Is there a way to reduce unnecessary/empty fields in SQL inserts and SQL updates?

For example, I have a single hibernate entity class mapped to a table that has 10 columns. The populating of data is actually done in two phases. When the user submit a request, I will insert the request information into the table with the hibernate entity, but populating only 7 fields. After some processing (wait for other users interaction for example), I will populate the remaining 3 fields (with the id given from the previous insert).

If I stick with a single entity class, for the second update, the steps I do is as follows:

1) Load the entity identified by id

2) Save the entity, which generates sql that seems to be sending all the fields over.

Alternatively, I created two entity class, and point to the same table and save them seperately.

Does anyone have a better suggestion?

Kent

Edit:

What I really like to achieve is something to the following effect: insert t(id,field1,field2) (?,?,?) update t set field3=? field4=? where id=?

The best I could achieve now with dynamicUpdate=true is insert t(id,field1,field2) (?,?,?) select field1,field2,field3,field4 from t where id=? update t set field3=? field4=? where id=?

Is there a way to eliminate that select statement? The original persisted object is not stored anywhere in memory after the insert.

An additional note. The entity class is annotated with Hibernate validation. I am currently trying out to achieve the above desired effect, so I commented them out. But when I turn them back on, I get validation errors due to @NotNull and @NotEmpty.

+2  A: 

If you add the annotation:

@org.hibernate.annotations.Entity(dynamicUpdate = true)

to the top of your entity only the fields that have changed will be sent to the database.

Sam
I tried it out, and it works. But is there a way to eliminate the step where I have to load the entity first? I would like to eliminate the extra 'select' statement to the database(assuming the entity is not cached in the session)
Kent Lai
I'm sure there are some hacks out their to achieve this.(e.g. keep the original object somewhere and then do a merge or use bulk update)However, if an extra select statement worries you perhaps hibernate isnt the right choice. For me its a question of performance vs maintainability.
Sam