【问题标题】:How to enable hibernate to set manually primary key?如何启用休眠手动设置主键?
【发布时间】:2021-10-31 23:28:41
【问题描述】:

拥有这些实体:

@Entity
@Data
@Builder
public class User {
    @Id
    private int id;
    private String name;
}

如果我尝试设置 id:

@Bean
    CommandLineRunner dataLoader(UserRepository userRepo){
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                User u = User.builder()
                        .id(1)
                        .name("First User")
                        .build();
                userRepo.save(u);
            }
        };
    }

我明白了

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:794) ~[spring-boot-2.5.3.jar:2.5.3]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:775) ~[spring-boot-2.5.3.jar:2.5.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:345) ~[spring-boot-2.5.3.jar:2.5.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.3.jar:2.5.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.3.jar:2.5.3]
    at com.example.demo.DemoApplication.main(DemoApplication.java:16) ~[classes/:na]
Caused by: org.springframework.orm.jpa.JpaSystemException: No default constructor for entity:  : com.example.demo.domain.User; nested exception is org.hibernate.InstantiationException: No default constructor for entity:  : com.example.demo.domain.User
...

如果我不设置id,那么没问题。那么如何手动设置主节点呢?

【问题讨论】:

标签: java spring hibernate jpa


【解决方案1】:

一般来说:您不应将@Data 与实体一起使用,因为如果您有双向实体,生成的equals/hashCodetoString 可能会导致StackOverflowError

回到你的问题,JPA 需要一个默认构造函数(没有 args 构造函数)

所以我会推荐这个:

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {
    @Id
    private int id;
    private String name;
}

【讨论】:

  • 1) 我不明白你StackoverfloError 的意思,你能举个例子吗? 2) 为什么@Builder 不提供默认(无参数)构造函数?为什么这会被 @Builder 覆盖? 3)为什么这个问题(关于缺少默认构造函数)通过​​添加@AllArgsConstrutor解决,这是不是默认构造函数?
  • 1) equals/hashCode/toString 将遵循引用并产生无限循环 2 和 3) 请阅读 API 文档projectlombok.org/api/lombok/Builder.html
  • 那么当使用@Data安全时,当使用@Entity时,会造成无限循环吗?什么时候没有?
  • 顺便说一句,您的注释还不够。无论如何它都会失败,除非提供了@AllArgsConstrutor。否则错误:constructor User in class com.example.demo.model.User cannot be applied to given types; required: no arguments found: int,java.lang.String reason: actual and formal argument lists differ in length
  • 你说得对,Builder 需要 AllArgsConstructor。
猜你喜欢
  • 2021-06-15
  • 1970-01-01
  • 2013-02-18
  • 2018-04-25
  • 2012-03-21
  • 2012-03-15
  • 2011-02-17
  • 2016-01-10
  • 2012-09-04
相关资源
最近更新 更多