我在休眠持久性方面存在这个问题:org.hibernate.id.IdentifierGenerationException:此类的ID必须在调用save()之前手动分配。这里有2个类,它们之间存在一对一的关系。我必须指定UserRole在MySql中成功创建,但是User没有。
@Entity @Table(name = "user") public class User { @Id private String id; @Column private String name; @Column private String email; @Column private String password; @OneToOne @JoinColumn(name = "userRole_id", referencedColumnName = "id") private UserRole userRole; public User() { }
@Entity @Table(name = "userRole") public class UserRole { @Id private String id; @Column private String description; @OneToOne(mappedBy = "userRole") private User user; public UserRole() { }
我有以下类UserRoleRepo和UserRepo
public class UserRepo { private EntityManagerFactory= entityManagerFactoryPersistence.createEntityManagerFactory("tutorial.lab.SD"); public void insertNewUser(User user) { EntityManager em = entityManagerFactory.createEntityManager(); em.getTransaction().begin(); em.persist(user); /////here I get the exception em.getTransaction().commit(); em.close(); } }
public class UserRoleRepo { private EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ro.tutorial.lab.SD"); public void insertNewUser(UserRole userRole) { EntityManager em = entityManagerFactory.createEntityManager(); em.getTransaction().begin(); em.persist(userRole); em.getTransaction().commit(); em.close(); } }
整个应用程序都在此类中运行。我必须指定此模板,我必须遵循它。另外,每个类中的Id必须为String类型。
public class ApplicationStart {
public static void main(String[] args) {
UserRoleRepo userRoleRepo= new UserRoleRepo();
UserRole userRole1 = new UserRole();
userRole1.setId(UUID.randomUUID().toString());
userRole1.setDescription("admin");
userRoleRepo.insertNewUser(userRole1);
UserRole userRole2 = new UserRole();
userRole2.setId(UUID.randomUUID().toString());
userRole2.setDescription("client");
userRoleRepo.insertNewUser(userRole2);
UserRepo userRepo= new UserRepo();
User user = new User();
user.setId(UUID.randomUUID().toString());
user.setName("Todoran");
user.setUserRole(userRole1);
userRepo.insertNewUser(user);
}
我在休眠持久性方面存在这个问题:org.hibernate.id.IdentifierGenerationException:此类的ID必须在调用save()之前手动分配。这是2个类别,它们之间...
对于一对一关系,我认为映射是错误的。尝试进行以下更改。在用户表中输入: