Reputation: 1965
Having these entity:
@Entity
@Data
@Builder
public class User {
@Id
private int id;
private String name;
}
If i try to set the 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);
}
};
}
I got
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
...
If i don't set the id, then no problem. So how do I can set the primary manually?
Upvotes: 0
Views: 889
Reputation: 36103
In General: You sholdn't use @Data
with Entities because the generated equals/hashCode
and toString
can lead to StackOverflowError
if you have bi-directional entities.
Coming back to your question JPA needs a default constructor (no args constructor)
So I would recommend this:
@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {
@Id
private int id;
private String name;
}
Upvotes: 2