Elena
Elena

Reputation: 61

Spring JPA CrudRepository save(Entity) is returning 0 in id field

I am adding spring JPA/Hibernate 5 to an old project. I am running CrudRepository .save(Entity) method against a Mainframe/DB2 table. The row is inserted just fine, but returnedEntity.getIdColumn() has 0 in it. I really need the ID for further processing. Could somebody please help? Thank you very much!

@Entity
Table(name="MY_TABLE")
public class myClass {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID_COLUMN")
private Long idColumn;
...

}

Identity is the only strategy type that worked. Here is the Service class:

@Transactional
public Entiry insertEntity(Entity originalEntity) {
   return MyRepository.save(originalEntity);
}
Runner class:
Entity originalEntity = createEntity();
Entity returnedEntity = ServiceClass.insertEntity(originalEntity);
System.out.println(originalEntity.getIdColumn());
System.out.println(returnedEntity.getIdColumn());

Upvotes: 4

Views: 7136

Answers (4)

iamtheexp01
iamtheexp01

Reputation: 3476

My ID column in DB table is set to auto increment. Here is the Java code that worked for me. Hope this helps.

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

Upvotes: 0

Leonid Dashko
Leonid Dashko

Reputation: 4154

Recently, I've faced with similar issue.

In my case, the new entity has been passed from UI and ID was 0 instead of NULL (since the type of ID was primitive on Java side). Therefore Hibernate didn't use right save strategy.

Eventually, I changed the type from long to Long and it helped:
private long id;
private Long id;

Also update method was changed from:

@PutMapping("/{id}")
public T update(@PathVariable ID id, @Valid @RequestBody T entity) {
    this.getService().update(entity);
    return entity;
}

to:

@PutMapping("/{id}")
public T update(@PathVariable ID id, @Valid @RequestBody T entity) {
    return this.getService().update(entity);
}

P.S.: When entity ID was 0, Hibernate was using merge strategy, however, it should persist strategy for new Entities instead (link for implementation of save method).

Upvotes: 1

Elena
Elena

Reputation: 61

Turned out my table had an id sequence generator already defined in the DB. So, after I changed it to generationType.SEQUENCE it worked nicely. @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MY_TABLE_SEQ")

Upvotes: 2

Andrew Preizner
Andrew Preizner

Reputation: 264

My guess is that you're trying to get an ID before your transaction was flushed to DB. Thus JPA doesn't know what id will be assigned and returns 0.

Edited: I'd recommend to have something like this:

@Transactional
public Entity save( .....) {
   //some code
   repository.save(entity);
   //some code
   return entity;
}

Transaction will be flushed at the end of this method and entity which will be returned from it should have a real id.

Upvotes: 3

Related Questions