Hibernate Save()选项不返回任何对象

时间:2016-12-24 01:12:07

标签: java hibernate

我是Hibernate的新手,我使用save()来将对象存储在数据库中

import java.io.*;//Bean Class
public class Employee implements Serializable
{
String name;
int age,id;

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() 
{
    return name;
}
public void setName(String name) 
{
    this.name = name;
}
public int getAge() 
{
    return age;
}
public void setAge(int age) 
{
    this.age = age;
}
}

public class Testclass1 //This is the Test Class
{   
    public static void main(String args[])
        {
        Employee eobj=new Employee();
        eobj.setName("Rajesh");
        eobj.setAge(23);        
        Configuration con=new Configuration();
        con.configure("Configuration1.xml");
        SessionFactory sf=con.buildSessionFactory();
        Session s=sf.openSession();
        Transaction t=s.beginTransaction();
        Object objectE=s.save(eobj);
        Employee Eobject=(Employee)objectE;
        System.out.println("Eage="+Eobject.getAge()+"EName="+Eobject.getName());
        t.commit();
        s.close();
        sf.close();
        }
}

我正在尝试获取该已保存对象并使用该已保存对象显示Id和Name。

但我得到了ClassCastException

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to com.online.javascript.Employee
    at com.online.javascript.Testclass1.main

1 个答案:

答案 0 :(得分:0)

异常非常明确。也就是说," session.save(eobj)返回object的id.Cant将其转换为Employee" 您可以通过

获取对象
emp =  (Employee ) session.get(Employee .class, id); // id = s.save(eemp)