0

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); ?

Ace
  • 1,501
  • 4
  • 30
  • 49

1 Answers1

1

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

Community
  • 1
  • 1
Shay Elkayam
  • 4,128
  • 1
  • 22
  • 19
  • Thanks Shay, that would surely do it. However I would like to minimize hibernate invocations as much as possible as it would cause performance degradations under high frequency loads. Id rather have a trigger that does that job for me. Will have to explore that route. – Ace Mar 19 '14 at 20:39
  • 1
    look at my update. I think it can be helpful for you. – Shay Elkayam Mar 19 '14 at 20:51
  • Thanks for the link. That's a very important piece of information. – Ace Mar 19 '14 at 21:04