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.  [ 1 post ] 
Author Message
 Post subject: sql-insert and entity identifier
PostPosted: Tue Jun 24, 2008 8:52 am 
Newbie

Joined: Tue Jun 24, 2008 8:04 am
Posts: 1
Location: Kharkiv, Ukraine
Hello.

I use custom sql-insert statement that calls stored procedure.
Code:
<class name="AST.PartnerSite20.Core.Domain.User, AST.PartnerSite20.Core.Dao">
      <id name="UserId" type="System.Int32" column="UserId" unsaved-value="0">
         <generator class="assigned"/>         
      </id>
      <property name="ClientId" type="System.Int32" not-null="true" />
      .......
<sql-insert check="none">
         exec up_User_i @ClientId=?, @Login=?, @FirstName=?, @LastName=?, @Email=?, @Password=?, @UserId=?
      </sql-insert>


And my stored proc looks like:

Code:
PROCEDURE [dbo].[up_User_i]
(
   @UserId INT =NULL OUT,
   @ClientId INT,
   @Login VARCHAR(50),
   @FirstName VARCHAR(50),
   @LastName VARCHAR(50),
   @Email VARCHAR(50),
   @Password VARCHAR(50)   
)
AS
BEGIN
   DECLARE @ResultCode INT

   -- Check if  user with the same login exists
   IF EXISTS(SELECT * FROM dbo.vw_Users WHERE Login=@Login)
      SET @ResultCode = -1;   
   ELSE BEGIN
      DECLARE @PrincipalId INT

      INSERT INTO dbo.tblUserPrincipals (ClientId, Type)
         VALUES(@ClientId, 'U')

      SET @PrincipalId = SCOPE_IDENTITY()
   
      INSERT INTO dbo.tblUsers (UserId, Login, FirstName, LastName, Email,Created,Password, ExpirePassword)
         VALUES (@PrincipalId, @Login, @FirstName, @LastName, @Email, GETDATE(),@Password, getdate())
         
      SET @ResultCode = @PrincipalId
      SET @UserId = @PrincipalId
   END
   
   SELECT @ResultCode AS ResultCode
END


As you can see Users primary key generated by stored procedure.


What should I do to obtain primary key, generated by stored proc or which approach is more preferable for me.

Also I tried to create custom generator (see bellow), but SCOPE_IDENTITY() doesn't work after procedure call and it's behavior is unpredictable.


Code:
public class StoredProcGenerator : IIdentifierGenerator
    {
        private const string sql = "SELECT SCOPE_IDENTITY()";

        #region IIdentifierGenerator Members

        [MethodImpl(MethodImplOptions.Synchronized)]
        public object Generate(ISessionImplementor session, object obj)
        {
            IDbConnection conn = session.Factory.OpenConnection();
            IDbCommand qps = conn.CreateCommand();
            qps.CommandText = sql;
            qps.CommandType = CommandType.Text;
            try
            {
                IDataReader rs = qps.ExecuteReader();
                if (rs.Read())
                {
                    if (!rs.IsDBNull(0))
                    {
                        return rs.GetValue(0);
                    }
                    else
                    {
                        throw new IdentifierGenerationException(
                            string.Format(CultureInfo.CurrentCulture,
                                          "Identifier generation failed: Sql query '{0}' have returned an identity with NULL value",
                                          sql));
                    }
                }
                else
                {
                    throw new IdentifierGenerationException(
                        string.Format(CultureInfo.CurrentCulture,
                                      "Identifier generation failed: Sql query '{0}' have returned 0 records", sql));
                }
            }
            finally
            {
                session.Factory.CloseConnection(conn);
            }
        }

        #endregion
    }


Thanks.


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

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.