У меня есть отношение один к одному между следующими 2 объектами:
@Entity
@Table(name = "user")
public class User {
@Id
@Column(name="id")
private String id;
@Column
private String name;
@Column
private String email;
@Column
private String password;
@OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
@JoinColumn(name = "user_role_id", referencedColumnName = "id")
private UserRole userRole;
@Entity
@Table(name = "userRole")
public class UserRole {
@Id
@Column(name="id")
private String id;
@Column
private String description;
@OneToOne(mappedBy = "userRole")
private User user;
public UserRole() {
}
Я также использую EntityManagerFactory для создания таблиц в моей локальной БД. Я получил этот код, и я должен следовать ему.
public class UserRepo {
private EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ro.tutorial.lab.SD");
public void insertNewUser(User user) {
EntityManager em = entityManagerFactory.createEntityManager();
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
em.close();
}
Также существует похожее UserRoleRepo.
Моя проблема заключается в создании экземпляра в main, я не знаю, как получить просто идентификатор UserRole для FK в User. Вместо этого я получаю весь экземпляр userRole и ошибку «Duplicate entry» b36fcb4 c -3904-4205-888b-9792f24d8b5 c 'для ключа' userrole.PRIMARY '".
public static void main(String[] args) {
UserRoleRepo userRoleRepo= new UserRoleRepo();
UserRole userRole1 = new UserRole();
userRole1.setId(UUID.randomUUID().toString());
System.out.println(userRole1);
userRole1.setDescription("admin");
userRoleRepo.insertNewUser(userRole1);
UserRole userRole2 = new UserRole();
userRole2.setId(UUID.randomUUID().toString());
System.out.println(userRole2);
userRole2.setDescription("client");
userRoleRepo.insertNewUser(userRole2);
UserRepo userRepo= new UserRepo();
User user = new User();
user.setId(UUID.randomUUID().toString());
user.setName("Todoran");
user.setEmail("todoran@utcluj.ro");
user.setPassword("mona");
user.setUserRole(userRole1); //////////it breaks here :(((((
System.out.println(user);
userRepo.insertNewUser(user);
}