简体   繁体   English

如何在Spring数据JPA中保存没有id的实体(休眠)

[英]How to save an entity without an id in Spring Data JPA (hibernate)

consider an entity with just an id and text field:考虑一个只有 id 和文本字段的实体:

@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();

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).在 JPA 中,实体 ID 可以由应用程序代码分配,也可以生成(由 JPA 提供程序,例如 Hibernate,或由数据库生成)。 In many situations, it's desirable to have the entity IDs be generated instead of applicaiton-assigned;在许多情况下,希望生成实体 ID 而不是应用程序分配; it seems like that's what you are expecting.看来这就是您所期望的。

If so, you need to annotate the id field with @GeneratedValue .如果是这样,您需要使用@GeneratedValue注释id字段。 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).这个 SO Answer也值得一读(作者是 JPA 和 Hibernate 的知名专家)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM