Hibernate:id值被保存为null

时间:2016-11-25 09:24:53

标签: hibernate jpa

我将Employee对象保存到Sql Server 2012中,但ID值始终为! [saved as null] 1, 我使用了策略标识,自动,顺序

员工类

@Entity
@Table(name="Employee")
public class Student {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
int id;
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
String name;
String email;
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}

DAO课程是: -

public class SaveDao {

SessionFactory factory = factorypattern.getfactory();
Session session = factory.openSession();
Transaction tx =session.beginTransaction();


// saving using save method with transaction so OK case
public void saveStudent() {

    System.out.println("******save method*****");

    try {
        Student student = new Student();
        student.setEmail("raja@gmail");
        student.setName("raja");
        session.save(student);
        tx.commit();
    } catch (HibernateException e) {
        tx.rollback();
    }
}

每当我使用

 SaveDao save=new SaveDao();

 save.saveStudent();

id null插入DB

1 个答案:

答案 0 :(得分:0)

尝试执行以下操作:

1)确保数据库在insert上生成id:

ALTER TABLE [yourTable] DROP COLUMN ID 
ALTER TABLE [yourTable] ADD ID INT IDENTITY(1,1)

2)使用IDENTITY策略

3)没有问题相关的想法,但是事务应该在方法中启动,而不是在DAO对象的类级别上