2016-11-25 64 views
0

我保存Employee对象到SQL Server 2012,但ID值始终! [saved as null]1, 我都用过的策略识别,自动,序列休眠:值id被保存为空

Employee类

@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("[email protected]"); 
     student.setName("raja"); 
     session.save(student); 
     tx.commit(); 
    } catch (HibernateException e) { 
     tx.rollback(); 
    } 
} 

每当我使用

SaveDao save=new SaveDao(); 

save.saveStudent(); 

ID空插在DB

回答

0

尽量做到以下几点:

1)确保你的数据库生成的插入IDS:

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

2)使用标识策略

3)没有问题相关的思想,但交易应该在方法中开始,而不是DAO对象的类级别

+0

它为我工作 – shashank