I have a problem when i try to save the user object to database using Spring Boot 2.1.6.RELEASE and Spring Data JPA.
- user object and detail object have a bidirectional one-to-one relation.
- The id of detail have a foreign key to id of user(the id of user is autoincrement).
- user information is map from json format to a object with @RequestBody.
json:
{"name" : "Jhon",
"detail":
{
"city" : "NY"
}
}
userController.java:
...
@PostMapping(value="/user")
public Boolean agregarSolicitiud(@RequestBody User user) throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
userRepository.save(user);
...
User.java:
...
@Entity
public class User {
@Id
@Column(updatable=false, nullable=false, unique=true)
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@OneToOne(mappedBy = "solicitud",optional=false,cascade=CascadeType.ALL)
private UserDetail userDetail;
}
UserDetail.java:
...
@Entity
public class UserDetail {
@Id
@Column
private Long id;
@Column
private String city;
@MapsId
@OneToOne(optional = false,cascade = CascadeType.ALL)
@JoinColumn(name = "id", nullable = false)
private User user;
}
userRepository.java
...
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
...
Error:
org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [proyect.model.Detail.user]
What can i do?
Thanks