[英]IDENTITY_INSERT with JPA
我試圖將一些假數據插入SQL Server Express數據庫。 我正在使用這樣一些簡單的代碼:
@Entity
@Table(name = "People")
public class Peeps implements Serializable {
@Id
@Column(name = "ID", columnDefinition = "Decimal(10,0)")
private String id;
@Column(name = "PERSON_NAME")
private String name;
}
我調用實體管理器創建上面的類,如下所示:
private EntityManager em = createManager();
private EntityTransaction utx = em.getTransaction();
final Peeps entity = new Peeps();
entity.setId("10002");
entity.setName("Joe");
utx.begin();
em.persist(entity);
utx.commit();
但是,這樣做時,我收到一個錯誤::
Cannot insert explicit value for identity column in table 'People' when IDENTITY_INSERT is set to OFF
所以我嘗試做的是這樣的:
em.createNativeQuery("SET IDENTITY_INSERT People ON").executeUpdate();
em.persist(entity);
em.createNativeQuery("SET IDENTITY_INSERT People OFF").executeUpdate();
但是,我仍然得到同樣的錯誤。 我的直覺使我相信連接沒有被分享。 在調用持久性之前,我可以做些什么來指示hibernate將IDENTITY_INSERT設置為ON嗎?
您缺少id字段下的下一行:
@GeneratedValue(strategy=GenerationType.IDENTITY)
所以你的id字段應如下所示:
@Entity
@Table(name = "People")
public class Peeps implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "ID", columnDefinition = "Decimal(10,0)")
private String id;
@Column(name = "PERSON_NAME")
private String name;
}
其次,您不應該自己為您的實體設置ID,當您使用hibernate持久化時,ID將自動生成。
所以擺脫: entity.setId("10002");
並且這樣做:
private EntityManager em = createManager();
private EntityTransaction utx = em.getTransaction();
final Peeps entity = new Peeps();
entity.setName("Joe");
utx.begin();
em.persist(entity);
utx.commit();
其他東西確保您在數據庫表中配置主鍵,並自動增加。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.