当前位置: 代码迷 >> Java Web开发 >> 有一个java有关问题困扰着小弟我。有关hibernate的
  详细解决方案

有一个java有关问题困扰着小弟我。有关hibernate的

热度:86   发布时间:2016-04-13 22:12:19.0
有一个java问题困扰着我。有关hibernate的
我将spring和hibernate做了一个整合,然后出现了一个结果我有点不懂。
这个是我的数据库的表

我的主键是id,然后我pid是int型
当我的数据字段都是有值的就可以顺利运行,
可是
当我把pid值变成了空值程序就报错了

Caused by: java.lang.IllegalArgumentException

然后我加了 在pid字段上面加了 nullable=true 也没啥卵用
而我把text 改为空,又不会出错。所以我在想是不是int型他就不能为空
或者有什么其他原因,求各位大神们给点招数
下面我上代码

这个是我的model映射数据库的类person

@Entity
@Table(name ="person")
public class person{
int id;
String text;
int pid;
String url;
@Id
@Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="text")
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Column(name="pid")
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
@Column(name="url")
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public person() {
// TODO Auto-generated constructor stub
}
public person(int id,String text,int pid,String url) {
// TODO Auto-generated constructor stub
this.id=id;
this.text=text;
this.pid=pid;
this.url=url;
}
}

这是我的dao类

@Repository
public class personDao {
private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
return sessionFactory;
}

@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

private Session getCurrentSession() {
return this.sessionFactory.getCurrentSession();
}

public person getById(Integer id){  
        return (person)this.getCurrentSession().get(person.class, id);  
    }  
public static void main(String arg[]){
//person p= new person(5,"员工",3, "a");
ApplicationContext act=new ClassPathXmlApplicationContext("spring-hibernate.xml","spring.xml");
personDao pd=(personDao) act.getBean("personDao");
person p1=pd.getById(4);

System.out.print(p1.getId()+" "+p1.getPid()+" "+p1.getText());
}
}


------解决思路----------------------
int默认为0,integer默认为null
------解决思路----------------------

在hibernate设置了在数据库也要设置可以为空
------解决思路----------------------
数据库字段不用改,改你java代码的字段类型把int改成integer。
------解决思路----------------------
如果你数据库没值,取出的数据就会为null
  相关解决方案