java - Hibernate 保存返回错误的生成 ID

标签 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", 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;
}

在数据库中,PK auto_Client_ID 已集群,设置为 IDENTITY(1,1)ClientInfoClientFam 记录均在数据库中创建,但 hibernate 返回 0。我也尝试从 save 捕获值,但它也是 0 .

我不想在单独的插入之间提交:事务是在所有插入都正常的情况下进行的(此后还有更多插入,但由于此 ID 问题我还无法访问它们)。

ClientFam 的模型几乎相同:id 字段也是 @GenerateValue(strategy=GenerationType.IDENTITY)

我还尝试为 ClientInfo 指定此项

@GeneratedValue(generator="increment", strategy=GenerationType.IDENTITY)
@GenericGenerator(name = "increment", strategy = "increment")

我第一次运行它时它返回了正确的值。但是,第二次运行时出现错误:

Cannot insert explicit value for identity column in table 'Report' when IDENTITY_INSERT is set to OFF

尝试就到此为止了。我到处查看的建议是使用 GenerationType.IDENTITY 作为数据库中的自动递增字段。这应该返回正确的值。我可能做错了什么?

我还尝试从右侧的 ClientInfo 对象本身获取 id(我认为应该将其写入其中),但它也是 0。让我觉得我的 ClientInfo 其中的模型和/或注释。

最佳答案

我发现我的情况存在问题 - 与 Hibernate 无关。有一个 而不是 insert 触发器不返回 id,因此弄乱了 save() 返回的内容。

关于java - Hibernate 保存返回错误的生成 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41599492/

相关文章:

java - 在 Android 中,如何有效地找到方法的调用者

PHP PDO (MSSQL) 无法获取输出参数

java - hibernate "IllegalArgumentException occurred calling getter"

java - getCurrentSession 给出 No Session Bound to Context,openSession 则没有

sql - 如何从 JSON 字符串读取具有长值的属性?

Hibernate envers,删除后事件抛出约束违反异常

java - ExecutorService java 可能的线程泄漏

java - 保持 spring 上下文 Activity ,直到 JMS 消息被消费

Java SQL 风格的数组操作

c# - 谁能告诉我为什么这个 SQL 查询不起作用