Home > Mobile >  How to save an entity without an id in Spring Data JPA (hibernate)
How to save an entity without an id in Spring Data JPA (hibernate)

Time:01-27

consider an entity with just an id and text field:

@lombok.Data
class Entity {
  @javax.persistence.Id
  UUID id;
  String name;
}

consider that the table definition is as follows:

create table entity (
  id uniqueidentifier not null primary key default newid(),
  name varchar(max)
);

I am then curious why this doesn't work and how i could make it work:

UUID savedId = entityRepository.save(new Entity().setName("entity name")).getId();

CodePudding user response:

In JPA, entity IDs can be either assigned by the application code, or generated (by the JPA provider, such as Hibernate, or by the database). In many situations, it's desirable to have the entity IDs be generated instead of applicaiton-assigned; it seems like that's what you are expecting.

If so, you need to annotate the id field with @GeneratedValue. For example:

class Entity {
    @Id
    @GeneratedValue
    UUID id;

    String name;
}

Note that there are considerations to be made regarding the generation strategy, so you'll want to educate yourself about them and make the right choice based on your situation. This is a good page that discusses the options. This SO Answer also is worth reading (the author is a well-known expert on JPA and Hibernate).

  • Related