Java 休眠保存返回错误的生成id
我在MSSQL Server 2012中使用Hibernate时遇到问题。无论我在尝试使用Hibernate在某个表中插入值时做了什么,我都会得到生成的id=0 这是模型Java 休眠保存返回错误的生成id,java,sql-server,hibernate,Java,Sql Server,Hibernate,我在MSSQL Server 2012中使用Hibernate时遇到问题。无论我在尝试使用Hibernate在某个表中插入值时做了什么,我都会得到生成的id=0 这是模型 @Entity @Table(name = "tbl_ClientInfo") public class ClientInfo { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column (name = "auto_Client_ID
@Entity
@Table(name = "tbl_ClientInfo")
public class ClientInfo {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column (name = "auto_Client_ID", unique=true, nullable=false)
private int auto_Client_ID;
...
这是我的信
public boolean addNewClient(Client client) {
// there is a class that wraps SessionFactory as singleton
Session session = getSessionFactory().openSession();
Transaction tx = null;
Integer clientFamId; //client family info id
Integer clientId; // actual client id
try {
// create fam info first with some data - need id for ClientInfo
tx = session.beginTransaction();
ClientFam clientFam = new ClientFam();
clientFamId = (Integer) session.save(clientFam);
clientFamId = (Integer) session.getIdentifier(clientFam); // this returns the right id
session.flush();
ClientInfo clientInfo = new ClientInfo();
clientInfo.setABunchOfFields(withStuff); //multiple methods
session.save(clientInfo);
clientInfoId = (Integer) session.getIdentifier(clientInfo); // this is always 0
session.flush();
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
return false;
} finally {
session.close();
}
return true;
}
在数据库中,PKauto\u Client\u ID
被聚集,设置为IDENTITY(1,1)
。数据库中创建了ClientInfo
和ClientFam
记录,但hibernate返回0。我还尝试从save
捕获值,但它也是0
我不想在单独的插入之间提交:事务是在所有插入都很好的情况下进行的(在此之后还有更多插入,但由于这个id问题,我还不能进行这些插入)
ClientFam的模型几乎相同:id字段也是@GeneratedValue(strategy=GenerationType.IDENTITY)
我还尝试为ClientInfo
@GeneratedValue(generator="increment", strategy=GenerationType.IDENTITY)
@GenericGenerator(name = "increment", strategy = "increment")
我第一次运行它时,它返回了正确的值。但是,第二次运行时,出现了一个错误:
当identity\u insert设置为OFF时,无法在表“报表”中插入identity列的显式值
这就是尝试的目的。我所看到的每一个地方都建议对数据库中的自动递增字段使用GenerationType.IDENTITY
。应该返回正确的值。我可能做错了什么
我还尝试从右边的
ClientInfo
对象本身获取id(我认为应该将其写入),但它也是0。让我觉得我的ClientInfo
模型和/或其中的注释有问题。这只是一个有根据的猜测,但您可能希望从@Column定义中删除“unique=true”子句。Hibernate可能将列作为唯一约束来处理,而不是主键。我发现我的情况存在问题-与Hibernate无关。有一个而不是insert
触发器没有返回id,因此弄乱了save()
返回的内容。谢谢@Thierry的回复。我以前也试过,结果也一样。我之前有过类似的@Column(name=“auto\u Client\u ID”)
。