Ace
Ace

Reputation: 1611

Hibernate Insert/Set?

Upon hibernate insert how do I set a column value as sum of pkey column and an hardcoded offest value.

@Column(name = "SUM_COLUMN", unique = true, nullable = false)
public void setSumColumn(Long sumColumn)
{
   this.sumColumn = pkey + 1000L;
}

Will this work upon session.save(myHibernateObj); ?

Upvotes: 0

Views: 172

Answers (1)

Shay Elkayam
Shay Elkayam

Reputation: 4158

This would not work as you expect, and that's why:

pkey is not available to an entity before it's persisted for the first time.

The proper way for you to do it will be:

1) create a new Entity (Entity myEntity = new Entity()).
2) set all the other fields you normally set for this entity (e.g name, etc..)
3) persist it.
4) Now you'll have it's id value available, so when you call setSumColumn, it will work as expected.

Please note (this is regarding the concern you've made in your comment about efficiency and "going to the database"): persist does not necessarily "go to" the database immediately.

so, you can still use this solution and effectively "save" the entity only once in the database. You can take a look at the following post for better understanding:

Hibernate EntityManager persist() and database round trip count

Upvotes: 1

Related Questions