损坏的休眠保存方法
我的 Java 应用程序的 DAO 层中有以下方法:
public void save(Employee emp) {
System.out.println("emp type: " + emp.getClass().getName);
getHibernateTemplate().save(emp);
System.out.println("object saved!");
System.out.flush();
}
员工类不从任何其他类扩展,并具有以下 hbm 文件:
<hibernate-mapping>
<class name="org.myCompany.Employee" table="employee">
<!-- fields omitted to save space -->
</hibernate-mapping>
然而插入失败并出现 java.lang.ClassCastException。起初,我认为我的映射有问题(比如整数映射到布尔值),但后来我打开了 hibernate 的 show_sql 调试并在日志文件中发现了以下内容:
员工类型:org.myCompany.Employee
休眠:插入客户 (.......) 价值观 (......)
java.lang.ClassCastException
为什么它选择一个完全随机的表来插入?我确信我一定有一些配置文件配置错误,但我不知道是哪一个。我检查了以下内容:
- applicationContext-hibernate.xml -> Customer 和 Employee 对象都映射到正确的 hbm 文件
- Customer 或 Employee 都没有继承关系(甚至没有像 Person 或 User 这样的公共父类)
我还能尝试什么?
I have the following method in my Java application's DAO layer:
public void save(Employee emp) {
System.out.println("emp type: " + emp.getClass().getName);
getHibernateTemplate().save(emp);
System.out.println("object saved!");
System.out.flush();
}
The employee class does not extend from any other classes and has the following hbm file:
<hibernate-mapping>
<class name="org.myCompany.Employee" table="employee">
<!-- fields omitted to save space -->
</hibernate-mapping>
Yet the insert fails with a java.lang.ClassCastException. At first, I thought something was wrong with my mapping (like an Integer mapping to a boolean) but then I turned on hibernate's show_sql debugging and found the following in my log file:
emp type: org.myCompany.Employee
Hibernate: insert into customer
(.......) values (......)
java.lang.ClassCastException
Why did it pick an entirely random table to insert into? I'm sure that I must have some config file mis-configured, but I don't know which one. I checked the following:
- applicationContext-hibernate.xml -> both the Customer and Employee objects are mapped to their correct hbm files
- neither Customer or Employee have an inheritance relationship (there isn't even a common parent class like Person or User)
What else could I try?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在调用类中,我有以下两个调用:
我认为客户对象已正确保存。我什至在两个调用之间放置了一条调试语句并打印了调试方法。但是,注释掉 UserDAO.saveCustomer 行解决了该问题。这使我更仔细地检查客户对象,发现它已损坏(错误的类)。 Hibernate 必须一直缓存插入语句,直到事务完成。
所以这个问题现在已经解决了。
In the calling class, I have the following two calls:
I thought that the customer object was saving correctly. I even put a debugging statement between the two calls and the debug method printed. However, commenting out the UserDAO.saveCustomer line fixed the problem. This made me examine the customer object more closely and I found that it was corrupt (wrong class). Hibernate must have been caching the insert statement until the Transaction was complete.
So this issue is now resolved.