-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: Problems with createSQLQuery and select scope_identity()
PostPosted: Thu Dec 10, 2015 11:36 am 
Newbie

Joined: Thu Dec 10, 2015 11:32 am
Posts: 2
I am forced to use createSQLQuery to insert values into tables with an Identity column (the first column and the primary key) using hibernate. Using hibernate classes are not an option since the tables are created on the fly for each customer that is added to the system. I have run the query and it successfully inserts into the table. I then execute a "select scope_identity()" and it always returns null. "select @@Identity" works but that is not guaranteed to be the correct one. I have also tried to append "select scope_identity()" to the insert query. Then I tried query.list() and query.uniqueResult() both of which throw the hibernate exception of "No Results ..."

Code:
    Session session = DatabaseEngine.getSessionFactory().openSession();
    String queryString = "insert into table1 (dataid) values (1)"
    SQLQuery query = session.createSQLQuery(insertQueryString);
    query.executeUpdate();
    query = session.createSQLQuery("select scope_identity()");
    BigDecimal entryID = (BigDecimal)query.uniqueResult();


The simple example table is defined as follows:
Code:
    "CREATE TABLE table1 (EntryID int identity(1,1) NOT NULL," +
    "DataID int default 0  NOT NULL, " +
    "PRIMARY KEY (EntryID))";


Is there a way I am missing to use scope_identity() with createSQLQuery?


Top
 Profile  
 
 Post subject: Re: Problems with createSQLQuery and select scope_identity()
PostPosted: Fri Dec 11, 2015 3:04 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania
Actually the `SQLServerDialect` class used by Hibernate uses the same "scope_identity()" too.

The reason why it's not working is because you need to execute those in the same statement or stored procedure.
If you execute the scope_identity() call in a separate statement, SQL Server will not be able to give you last inserted identity value.

You cannot do it with the `SQLQuery`, even Hibernate uses JDBC to accomplish this task. I wrote a test on GitHub to emulate it.

The code looks like this:

Code:
    Session session = entityManager.unwrap(Session.class);
    final AtomicLong resultHolder = new AtomicLong();
    session.doWork(connection -> {
        try(PreparedStatement statement = connection.prepareStatement("INSERT INTO post VALUES (?) select scope_identity() ") ) {
            statement.setString(1, "abc");
            if ( !statement.execute() ) {
                while ( !statement.getMoreResults() && statement.getUpdateCount() != -1 ) {
                    // do nothing until we hit the resultset
                }
            }
            try (ResultSet rs = statement.getResultSet()) {
                if(rs.next()) {
                    resultHolder.set(rs.getLong(1));
                }
            }
        }
    });
    assertNotNull(resultHolder.get());


The code uses Java 8 lambdas instead of anonymous classes, but you can easily port it to Java 1.7 too.


Top
 Profile  
 
 Post subject: Re: Problems with createSQLQuery and select scope_identity()
PostPosted: Fri Dec 11, 2015 1:16 pm 
Newbie

Joined: Thu Dec 10, 2015 11:32 am
Posts: 2
Thanks Vlad,
That works great!!!


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.