提问者:小点点

如何启用hibernate手动设置主键?


拥有这些实体:

@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,那没问题。那么如何手动设置主?


共1个答案

匿名用户

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

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

所以我推荐这个:

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