0

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();
E-Riz
  • 31,431
  • 9
  • 97
  • 134
Dave Ankin
  • 1,060
  • 2
  • 9
  • 20

1 Answers1

1

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).

E-Riz
  • 31,431
  • 9
  • 97
  • 134
  • this still generates the id client side, i am trying to generate it on the server side. additionally, if my default was "CURRENT_TIMESTAMP", this annotation did not help, i had to add @Column(updatable=false, insertable=false) - so I am wondering what is the general approach – Dave Ankin Jan 27 '23 at 14:23
  • What do you mean by "server side?" In the RDBMS? – E-Riz Jan 27 '23 at 14:24
  • correct, i want jpa to not manager it whatsoever, no column value = do not put it in the insert statement. – Dave Ankin Jan 27 '23 at 14:25
  • oh, GeneratedValue is PK specific – Dave Ankin Jan 27 '23 at 14:26
  • Personally I usually choose `@GeneratedValue(strategy = GenerationType.AUTO)` but it's not a one-size-fits-all situation. Different database vendors support different options. The page I linked to in the answer explains it pretty well. – E-Riz Jan 27 '23 at 14:27