in Java

Hibernate Persistent保存到MySQL碰到的问题

小结

记录下Hibernate Persistent保存到MySQL碰到的几个问题,及其解决方法。

问题及解决

Unknown column ‘xx’ in ‘field list’

也就是保存到数据库里时找不到相应的字段,这里需要检查一下数据库或者xxx.hbm.xml的配置文件。例如:

    <!--定义count和表字段的映射-->
    <property
        name="count"
        type="int"
        column="count"
        not-null="true"
        length="4"
    >

以上需要确保数据库中有这样一个count的字段。

错误的使用了Update方法,应该为Save方法

使用Hibernate的Update方法是更新已有的数据项,如果需要插入新数据项,则需要使用Save方法。
具体返回错误如下:

The given object has a null identifier: xxx.xxx.xxx on hibernate update

对于更新已有的数据项,需要实现update方法:

    public void update(xxx xxx) {
        this.getHibernateTemplate().update(xxx);
    }

对于插入新数据项,需要实现insert方法:

    public void insert(xxx xxx) {
        this.getHibernateTemplate().save(xxx);
    }

保存对像时传入空指针

具体返回错误如下:

java.lang.IllegalArgumentException: attempt to create saveOrUpdate event with null entity

在以上保存或者插入数据项时,如果传入的对象是空的,则会返回以上错误。

参考

Caused by: org.hibernate.TransientObjectException: The given object has a null identifier: com.models.User on hibernate update
java.lang.IllegalArgumentException: attempt to create event with null entity

Write a Comment

Comment