I Have two models, One is used to store user details and with that Id, I'm trying to save the user location in another table, which uses the same id of the user as the primary key.
User Model
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(unique = true)
private String username;
@Column(unique=true)
private String email;
private String password;
private String Role;
@OneToOne(mappedBy = "user")
private UserLocation location;
//...constructors, getters and setters
}
UserLocation Model
@Entity
public class UserLocation {
@Id
private Long id;
@OneToOne(cascade = CascadeType.MERGE)
@JoinColumn(name="id")
@MapsId
private User user;
private Point location;
//...constructors, getters and setters
}
My Spring Boot Application class where I try to insert records to both the table
@SpringBootApplication
public class ContainmentZoneAlertApp implements CommandLineRunner {
@Autowired
private UserlocationRepository userLocRepo;
@Autowired
private UserRepository userRepo;
public static void main(String[] args) {
SpringApplication.run(ContainmentZoneAlertApp.class, args);
}
@Override
public void run(String... args) throws Exception {
UserLocation userLocation = new UserLocation();
Geometry geometry = GeometryUtil.wktToGeometry(String.format("POINT (13.0827 80.2707)"));
//GeometryUtil is a utility class
User user = new User(null,"user 3","user3@gmail.com","hello123","user");
user = userRepo.save(user);
userLocation.setUser(user);
userLocation.setLocation((Point)geometry);
userLocRepo.save(userLocation);
}
}
Im getting
caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.saravanan.models.User
Why am I getting this error? and what does persist mean? & I'm using MySQL database