2

我已经成功创建了两个实体之间的一对一映射。我能够从这两个表中检索数据,但是我无法执行插入。

@Entity
@Table(name="users_test")
public class User {
    @Id
    @Column(name="user_id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String username;
    private String password;
    private int enabled;

    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    private UserRole userRole;

       //getters and setters
}

@Entity
@Table(name = "user_roles")
public class UserRole {
    private int user_role_id;
    @Id
    @GeneratedValue(generator = "gen")
    @Column(name = "user_id", unique = true, nullable = false)
    @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="user"))
    private int user_id;
    private String authority;

    @OneToOne(mappedBy="userRole", cascade=CascadeType.ALL)
    private User user;

        //getters and setters
}

我能够通过此映射成功地从表中读取值,但是当我尝试将数据插入表中时出现错误。

public class Runner {
    public static void main(String[] args) {
        Runner run = new Runner();
        ApplicationContext context = new FileSystemXmlApplicationContext("E:\\applicationContext.xml");

        UserDao userDao = (UserDao) context.getBean("userDao");


        UserRole userRole = new UserRole();
        userRole.setAuthority("USER_ROLE");
        userRole.setUser_role_id(0);

        User user = new User();
        user.setUsername("ichigo");
        user.setPassword("kura");
        user.setEnabled(0);
        user.setUserRole(userRole);
        userDao.insertUser(user);
    }

}

用户道:

@SuppressWarnings("unchecked")
@Repository
@Transactional
public class UserDao {
    @Autowired
    SessionFactory sessionFactory;

    public List<User> getUsers() {
        Session currentSession = sessionFactory.getCurrentSession();
        return currentSession.createQuery("from User").list();
    }

    public void insertUser(User user) {
        sessionFactory.getCurrentSession().save(user);
    }
}

我得到以下异常:

Exception in thread "main" org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [test.hibernate.model.UserRole.user]
    at org.hibernate.id.ForeignGenerator.generate(ForeignGenerator.java:101)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:118)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:114)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:724)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:716)
    at org.hibernate.engine.spi.CascadingAction$5.cascade(CascadingAction.java:258)
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:380)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:323)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:208)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:165)
    at org.hibernate.event.internal.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:448)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:293)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:204)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:189)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:753)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:745)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:741)
    at test.hibernate.dao.UserDao.insertUser(UserDao.java:24)
    at test.hibernate.dao.UserDao$$FastClassByCGLIB$$192f03a.invoke(<generated>)
    at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
    at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
    at test.hibernate.dao.UserDao$$EnhancerByCGLIB$$7428e072.insertUser(<generated>)
    at test.hibernate.test.main.Runner.main(Runner.java:34)

请就我做错了什么提出建议。


编辑:

从回复看来,我的外键混杂在了代码中。所以只要把问题说清楚,我正在发布表格的架构。

    CREATE TABLE `users_test` (                              
                  `USER_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,    
                  `USERNAME` varchar(45) NOT NULL,                       
                  `PASSWORD` varchar(45) NOT NULL,                       
                  `ENABLED` tinyint(1) NOT NULL,                         
                  PRIMARY KEY (`USER_ID`)                                
                ) ENGINE=InnoDB AUTO_INCREMENT=113 DEFAULT CHARSET=utf8  

CREATE TABLE `user_roles` (                                                                                                   
              `USER_ROLE_ID` int(10) DEFAULT NULL,                                                                                        
              `USER_ID` int(10) unsigned NOT NULL,                                                                                        
              `AUTHORITY` varchar(45) NOT NULL,                                                                                           
              PRIMARY KEY (`USER_ID`),                                                                                                    
              KEY `FK_user_roles` (`USER_ID`),                                                                                            
              CONSTRAINT `FK_user_roles` FOREIGN KEY (`USER_ID`) REFERENCES `users_test` (`USER_ID`) ON DELETE CASCADE ON UPDATE CASCADE  
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8  
4

3 回答 3

2

您的一对一映射也是错误的,外键使用不正确。在您的示例中,外键使用错误。您的映射表明primary keyofUserRoleforeign keyUser,但不是。您需要删除@PrimaryKeyJoinColumn和映射外键@JoinColumn

有两种类型的一对一映射。

单向映射

只有对象的欠侧在关系中被映射。对象没有出现在关系的另一边。

@Entity
@Table(name="users_test")
public class User {
    @Id
    @Column(name="user_id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String username;
    private String password;
    private int enabled;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private UserRole userRole;

       //getters and setters
}

由于使用了双向映射,因此UserRole类将没有任何内容。User

@Entity
@Table(name = "user_roles")
public class UserRole {

    @Id
    @GeneratedValue(generator = "gen")
    @Column(name = "user_role_id", unique = true, nullable = false)
    @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="user"))
    private int user_role_id;
    private String authority;

}

双向映射

这两个类都具有这种映射样式的关系。mappedBy此处使用的属性强调关系的欠侧。不需要第二个外键,只需使用适当的映射添加User对象即可。在您的情况下,它不是UserRole由映射的。useruserRole

@Entity
@Table(name = "user_roles")
public class UserRole {

    @Id
    @GeneratedValue(generator = "gen")
    @Column(name = "user_role_id", unique = true, nullable = false)
    @GenericGenerator(name="gen", strategy="foreign", parameters=@Parameter(name="property", value="user"))
    private int user_role_id;
    private String authority;

    @OneToOne(mappedBy="user", cascade=CascadeType.ALL)
    private User user;

        //getters and setters
}

编辑

还有另一个错误的映射。UserRole#user_role_id是用 . 注释的外键@Id

于 2013-09-18T06:06:54.447 回答
0

您具有双向关系,但仅设置关系的一侧。你只是在做user.setUserRole(userRole)。你需要做一个userRole.setUser(user)to,我喜欢在 setter 中这样做setUserRole()

public clas User {

    public void setUserRole(UserRole userRole) {
        this.userRole=userRole;
        this.userRole.setUserRole(this);
    }

}

这种方式总是被处理。(您可能还需要/想要添加null支票)。

您的代码中还有一件奇怪的事情,为什么您的UserRole对象有一个User和一个user_id字段?恕我直言,它应该只有一个User字段。

@Entity
@Table(name = "user_roles")
public class UserRole {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int user_role_id;

    private String authority;

    @OneToOne(mappedBy="user", cascade=CascadeType.ALL)
    private User user;

    //getters and setters
}

我会期待像上面这样的东西。

于 2013-09-18T06:06:08.037 回答
-1

首先,据我所知,用户和角色实体之间的一对一映射是不正确的。您可能希望您的用户拥有多个角色,对吗?

UserRole 实体不应有对 User 的引用 - UserRole 可以在没有 User 的情况下存在。

一个用户可以有多个角色,一个角色可以分配给多个用户。(假设这是您打算做的。)

我建议您使用单向多对多或用户和用户角色实体之间的关系。它将为 User-UserRole 映射创建一个单独的表。

例子:-

class User {

     //  ID and other fields


     @ManyToMany(fetch = FetchType.EAGER)
     @JoinColumn(unique = false, nullable = false, name = "ROLE", insertable = true)
     @Fetch(value = FetchMode.JOIN)
     @JoinTable(name="USER_ROLE_MAPPING")
     private List<UserRole> authorities;
}

角色实体:-

class UserRole{

     // id and other fields.

      private String roleName;    // Thats it !!
}
于 2013-09-18T06:08:49.653 回答