2016-11-25 37 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