Hibernate保存数据时引用为空的外键异常

Exception in thread "main" org.hibernate.PropertyValueException: not-null property references a null or transient value: com.ntcsoft.domain.UserTb.staticUserrights


//用户表
CREATE TABLE USER_TB(
USER_ID NUMBER(8) PRIMARY KEY NOT NULL,//主键 非空 自动增长
USER_NAME VARCHAR2(15) NOT NULL, //用户登录ID
USER_PASSWD VARCHAR2(15) NOT NULL,//用户登录密码
USER_ASK_QUESTI VARCHAR2(100),//用户密码查询问题
USER_ASK_ANSWER VARCHAR2(50),//用户密码查询答案
F_USER_RIGHTS_ID NUMBER(8) DEFAULT 3 NOT NULL,//引用用户权限表中USERRIGHTSID的外键
}

public class UserTb implements java.io.Serializable {
private Integer userId;
private StaticUserrights staticUserrights;
private PageSet pageSet;
private String userName;
private String userPasswd;
}

//权限表
CREATE TABLE STATIC_USERRIGHTS(
USER_RIGHTS_ID NUMBER(8) PRIMARY KEY NOT NULL,//主键 非空 自动增长 --用户权限ID 1:系统管理员 2:普通用户 3:游客
USER_RIGHTS_DES VARCHAR2(50)//用户权限描述
);

public class StaticUserrights implements java.io.Serializable {
private Integer userRightsId;
private String userRightsDes;
private Set userTbs = new HashSet(0);
}


//编辑用户信息
public void save(UserTb instance) {
getSession().saveOrUpdate(instance);
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserTbDao dao = (UserTbDao) context.getBean("userTbDao");
StaticUserrightsDao staticUserrightsDao = (StaticUserrightsDao) context.getBean("staticUserrightsDao");
UserTb instance=new UserTb();
instance.setUserName("ee");
instance.setUserPasswd("ee");
dao.save(instance);
//新增用户的时候,如果直接用Hibernate往数据库插数据的时候,(权限默认是3,所以我就没有再指定),就报以上错误!
}

//解决办法
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserTbDao dao = (UserTbDao) context.getBean("userTbDao");
StaticUserrightsDao staticUserrightsDao = (StaticUserrightsDao) context.getBean("staticUserrightsDao");
UserTb instance=new UserTb();
instance.setUserName("ee");
instance.setUserPasswd("ee");
instance.setUserNickname("ee");
StaticUserrights staticUserrights = staticUserrightsDao.findById(3);//查询权限是3的“权限”然后再set给用户即可
instance.setStaticUserrights(staticUserrights);
dao.save(instance);
System.out.println("======");

发表评论

邮箱地址不会被公开。 必填项已用*标注

昵称 *