如何返回Id插入存储过程+ mybatis

时间:2014-02-07 21:46:37

标签: java sql-server mybatis

我有一个返回ID的存储过程(sql server 2005):

BEGIN
    INSERT INTO 
      rolTemplateWeek(rolWeek,employee,date_insert) 
      VALUES(@numberRol,@employeeId,getDate())
   Select @id = @@IDENTITY
END

Mapper.xml

    <insert  id="saveRol" parameterType="com.service.specual.dto.RolWeek" statementType="CALLABLE">
    { call saveRolWeek(
        #{numberRol,javaType=Integer,jdbcType=INTEGER,mode=IN},
        #{employeeId,javaType=Integer,jdbcType=INTEGER,mode=IN},
        #{id,javaType=Integer,jdbcType=INTEGER,mode=OUT}
    )}
</insert>

RolWeek.class

    public class RolWeek {

    private int id;
        private int numberRol;
    private int employeeId;
        .... get & setters

Mapper.java

   RolWeek rolWeek= new RolWeek ();
   rolWeek.setNumberRol(120);
   rolWeek.setEmployeeId(100);

   public int saveServiceRolWeek(RolWeek rolWeek);

插入正常但不返回我的ID,仅返回“1”¿我如何返回插入的ID?

1 个答案:

答案 0 :(得分:1)

--
-- Use output clause, make sure id is OUTPUT
--

CREATE PROCEDURE saveRolWeek
   @numberRol INT,
   @employeeId INT,
   @id INT OUTPUT
AS
BEGIN

    SELECT @id =
      INSERT INTO rolTemplateWeek(rolWeek, employee, date_insert) 
      OUTPUT INSERTED.ID
      VALUES(@numberRol, @employeeId, getDate());
END

-- Sample call with 1, 1 as parameters
DECLARE @retid int = null;
EXECUTE dbo.saveRolWeek 1, 1, @retid = @id OUTPUT;