![](/img/trans.png)
[英]foreign key constraint in One To One relationship in JPA hibernate
[英]Foreign Key in One to One RelationShip Hibernate
我在以下 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 中實例化時,我不知道如何僅獲取 User 中 FK 的 UserRole id。 相反,我得到了 userRole 的整個實例和錯誤“Duplicate entry 'b36fcb4c-3904-4205-888b-9792f24d8b5c' for key '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);
}
似乎我感到困惑,正確的關系是 UserRole 和 User 表之間的一對多關系。 現在它工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.