How to identify an object is transient or detached in hibernate?

前端 未结 5 785
無奈伤痛
無奈伤痛 2021-01-01 16:04

I know that transient instance means the instance is newly created and its corresponding row does not exist in the database where as detached instance has corresponding entr

5条回答
  •  情话喂你
    2021-01-01 16:55

    You can try pass a transient object and a detached object to hibernate session update method and watch the difference.For transient object, hibernate will report an error.

    So hibernate knows the object is transient or detached. But how? The answer is simple: hibernate will do an select before the update to get the information of which fields are dirty. If the object is transient, the will be no result of that selection operation then hibernate knows this is transient object and report an error.

    Or, if you use @SelectBeforeUpdate(false), hibernate will not do the select, instead with an update directly, in this case, jdbc will report error due to the row need to update is not exist.

    Of course you can check the id field if it generated by database or else the only way to know its state is do an query: not found means transient.

提交回复
热议问题