user3708842
user3708842

Reputation: 563

Can Hibernate automatically select after insert?

I am inserting an object into a table using Hibernate saveOrUpdate(object). This object does have an automatically generated ID field and also a 'createdDate' field that is set by the database upon insert. After the insert, the ID field in the java object has the new generated value, but the 'createdDate' field is still null.

Is there a way (configuration or setting or parm) that can tell Hibernate to select the new row automatically after the insert is done, so that the Java object in memory is completely filled out? After the user 'saves' the object the webpage stays open on this object for the user to edit more fields (that are only available after the initial insert), so I want to show these generated fields ( ID, createdDate ) to the user.

** EDIT **

Due to an answer, I'm adding the HBM.XML file for the object:

<hibernate-mapping>
  <class name="MyObject" table="MyObject">
      <id name="objectId" type="java.lang.Integer">
          <column name="Object_ID" />
          <generator class="identity" />
      </id>
      . . .  other attributes . . .
      <property name="createdDate" type="timestamp" update="false" insert="false">
          <column name="Created_Date" not-null="true" />
      </property>
  </class>
</hibernate-mapping>

Upvotes: 0

Views: 969

Answers (1)

JB Nizet
JB Nizet

Reputation: 691973

Annotate the property with @Generated

@Generated(GenerationTime.INSERT)
private Date creationDate;

Note that this will have a cost. You could simply generate the creationDate in the code, and not in the database (using a listener or a JPA @PrePersist annotation).

Upvotes: 1

Related Questions