我正在尝试将一些假数据插入到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?