Java 一对一关系中的外键休眠
我在以下两个实体之间有一对一的关系:Java 一对一关系中的外键休眠,java,hibernate,foreign-keys,persistence.xml,hibernate-entitymanager,Java,Hibernate,Foreign Keys,Persistence.xml,Hibernate Entitymanager,我在以下两个实体之间有一对一的关系: @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; @O
@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;
我还使用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中实例化时,我不知道如何仅获取FK-in用户的UserRole id。相反,我得到了整个userRole实例和错误“重复条目‘b36fcb4c-3904-4205-888b-9792f24d8b5c’作为键‘userRole.PRIMARY’”
看起来我很困惑,正确的关系是UserRole和User表之间的一对多关系。现在它工作得很好
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();
}
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);
}