我正在练习一个简单的Hibernate程序并遇到了一个奇怪的问题。
我的模特:
public class Employee implements java.io.Serializable {
// Fields
private Integer empId;
private String empName;
private BigDecimal empSal;
//setters and getters
我的测试课程:
public static void main(String[] args) {
Configuration config = new Configuration();
config.configure("hibernate.cfg.xml");
SessionFactory factory = config.buildSessionFactory();
Session session = factory.openSession();
Employee emp = new Employee();
emp.setEmpName("abc");
emp.setEmpSal(new BigDecimal("100000"));
Transaction t = session.beginTransaction();
session.save(emp);
t.commit();
System.out.println("Object Saved Succesfully!!");
session.close();
factory.close();
}
我得到的例外:
Exception in thread "main" org.hibernate.InstantiationException: could not instantiate test objectcom.gbn.model.Employee
at org.hibernate.engine.UnsavedValueFactory.instantiate(UnsavedValueFactory.java:25)
at org.hibernate.engine.UnsavedValueFactory.getUnsavedIdentifierValue(UnsavedValueFactory.java:44)
at org.hibernate.tuple.PropertyFactory.buildIdentifierProperty(PropertyFactory.java:44)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:123)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:434)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:109)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:55)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:226)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1294)
at com.gbn.test.Test.main(Test.java:19)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.engine.UnsavedValueFactory.instantiate(UnsavedValueFactory.java:22)
... 9 more
Caused by: java.lang.Error: Unresolved compilation problem:
The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files
at com.gbn.model.Employee.<init>(Employee.java:1)
... 14 more
如果我没有在Employee模型中实现Serializable,我可以毫无问题地保存数据。只有当我的pojo实现Serializable时才会出现这个问题。
导致问题的原因是什么?
我按照建议here和here尝试了解决方案,但无法解决我的问题。
hbm文件:
<hibernate-mapping>
<class name="com.gbn.model.Employee" table="EMPLOYEE">
<id name="empId" type="java.lang.Integer">
<column name="EMP_ID" precision="22" scale="0" />
<generator class="increment" />
</id>
<property name="empName" type="java.lang.String">
<column name="EMP_NAME" length="20" />
</property>
<property name="empSal" type="java.math.BigDecimal">
<column name="EMP_SAL" precision="22" scale="0" />
</property>
</class>