关于使用Hibernate出现的多种常见错误的原因及解决办法

来源:互联网 发布:玩淘宝要费多少流量 编辑:程序博客网 时间:2024/06/08 13:39

使用saveOrUpdate方法update数据表失败。

报错提示:A different object with the same identifier value was already associated with the session。

原因解释:在Hibernate中同一个session里面有两个相同标识但是是不同实体

具体案例
有一个数据表名为:student包含字段id、name、num。
在java中有两个实体,分别为StudentInfo和StudentInfoTmp,均包含id、studentName、studentNum属性。
如果此时在Hibernate配置文件中将两个实体均配置到同一session,当使用saveOrUpdate方法进行update时,将会出现此类错误。

解决办法
(1)最好是在开发的过程中避免此类情况的出现,保证同一session中只有唯一标识;
(2)如果无法避免可以使用merge方法实现update,或者参考网上的其他解决办法。
参考链接:
http://www.myexception.cn/powerdesigner/879735.html
http://blog.sina.com.cn/s/blog_4b5bc01101016nii.html

无法解析属性

报错提示:could not resolve property

原因解释:在sql语句中出现了无法解析的属性名,最常见的错误是应用了数据表的属性名,而应该使用实体类的属性名。

具体案例
有一个数据表名为:student包含字段id、name、num。
在java中实体为StudentInfo,包含id、studentName、studentNum属性。
若更新数据表是想用以下命令:”update StudentInfo t set t.name = ‘” + name + “’, t.num = ‘” + num + “’ where t.id = ‘” + id +”’”,将会出现此类错误。
正确的命令应该为:”update StudentInfo t set t.studentName = ‘” + name + “’, t.studentNum = ‘” + num + “’ where t.id = ‘” + id +”’”。

解决办法:仔细检查属性名并改正。

其他注意事项

所有内容均用单引号括起来,字符串整型数据都需要

报错提示:unexpected token(意外标记)

不能将字符串数据赋值给整型字段,否则会导致sql命令不能正常执行

当实体类属性为null(空)时,最好不要更新对应数据表的字段

(1)当实体类整型属性为null时,会将“null”作为字符串值进行传递,会导致错误。
(2)需要在update之前对判断属性是否为null,否则,数据表中的NULL(空)字符串字段会被替换为“null”字符串。

1 3