0

first of all, I don't speak english correctly, so, sorry for the mistakes.

I having a problem, when I try to create a entity (with id NULL, then the database will assign it) and the creation fails, the entity is left with the generated ID. I need that the id remain null if the creation fails, because in my service, I check if the entity passed to "save" method, contains ID or not, to make an update or an create.

I can set the ID in null if the creation fails, but when I making more complex transactions, is hard to change manually every ID in every entity, and some times, some objects are fetched from the database and others not.

I hope that I have explained correctly... Thanks.

PD: This is the field ID in the entity...

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;

PD2: I using Spring framework by the way.

EDIT: I using PostgreSQL, and try every generation posible.

Enzo
  • 95
  • 1
  • 5

3 Answers3

2

From the design perspective you should rely on exceptions not on null values.

In your service you can just catch the exception and you don't have to add if statement.

Tomiak
  • 78
  • 6
0

Much depends on the DB you are using , the generation method and the Hibernate Dialect.

In many situation the DB will assign the ID and Hibernate will just load the field with that value.

Looking a bit into both dialect and Postgres I think that you will have to undo id by hand, since postgres sequences are not affected by rollback (see this answer) so hibernate can get the current ID even for failed inserts.

You could use JPA lifecycle annotation to collect enough information about your entity to do a clean up after a failed save.

Community
  • 1
  • 1
minus
  • 2,646
  • 15
  • 18
0

The IDENTITY generation strategy is not commonly preferred and here is why: Hibernate cannot generate an identifier value before an INSERT operation. That's why Hibernate has to perform the INSERT query and SELECT immediately after it. In this way, Hibernate will populate the identifier value of your persisted entity instance.

I believe that PostgreSQL doesn't support the IDENTITY id generation strategy (Hibernate Identity, Sequence and Table (Sequence) Generator). If PostgreSQL supported the IDENTITY strategy, then your entities would not have id initialized because SELECT would never happen.

vhula
  • 487
  • 2
  • 9