返回存储函数的结果

时间:2015-03-05 13:55:29

标签: java sql oracle mybatis

我们正在使用Oracle SQL,MyBatis和Java。

我目前只是尝试使用一个Long参数执行存储函数,然后返回结果(也是Long值)。

DAO.java

public interface ProjectDao {
    Long createProject(Long ownerId);
}

DAO.xml

<select id="createProject" resultType="Long" parameterType="Long" statementType="CALLABLE">
    {
        call COMPANY.PKG_PROJECT.CREATE_PROJECT(#{id})
    }   
</select>

我尝试了各种各样的方法但显然我的MyBatis知识在这里结束了。

PKG_PROJECT

FUNCTION CREATE_PROJECT(p_ID IN NUMBER) RETURN NUMBER IS r_ID NUMBER;

BEGIN
    DECLARE boolOwnerFound NUMBER := 0;
    r_ID NUMBER := NULL;
    BEGIN
      -- Workaround for "IF EXISTS"
      SELECT COUNT(*) INTO boolOwnerFound FROM owner o WHERE o.id = p_ID AND rownum <= 1;
      IF boolOwnerFound = 1 THEN
        BEGIN
          INSERT INTO 
            project (owner_id) 
          VALUES 
            (p_ID) 
          RETURNING 
            project.id INTO r_ID;
        END;
      END IF;
      RETURN r_ID;
    END;

END CREATE_PROJECT;

我想按给定的所有者ID创建项目(如果该所有者存在),然后返回新生成的项目的id。

2 个答案:

答案 0 :(得分:0)

如果要在函数中执行此操作,则应将其设置为自治事务。这种功能的结构将是这样的。

create or replace function...
pragma autonomous_transaction;
begin
  ...
    insert
  ...
  commit;
  return id;
exception
  when others then rollback;
  raise;
  -- or return null value?
end;

缺点是提交无法完成。调用该函数后,将提交数据。

答案 1 :(得分:0)

看了out parameters,因为ruudvan的评论表明我已经能够提出解决方案/解决方法。

DAO.java

public interface ProjectDao {
    void createProject(DVOCreateProject dvo);
}

DVOCreateProject.java

public class DVOCreateproject {
    private long ownerID;
    private long projectID;

    ... getter & setter ...
}

DAO.xml

<select id="createProject" parameterType="company.project.DVOCreateProject" statementType="CALLABLE">
  {
    call COMPANY.PKG_PROJECT.CREATE_PROJECT (
        #{ownerId,   mode=IN,  jdbcType=NUMERIC},
        #{projectId, mode=OUT, jdbcType=NUMERIC}
        )
  }   
</select>

PKG_PROJECT

  PROCEDURE CREATE_PROJECT(p_Owner_ID     IN  NUMBER,
                           p_Project_ID   OUT NUMBER) AS

  v_boolTaskownerFound      NUMBER;

  BEGIN
    SELECT COUNT(*) INTO boolOwnerFound FROM owner o WHERE o.id = p_Owner_ID AND rownum <= 1;
    IF v_boolOwnerFound = 1 THEN
      BEGIN
        INSERT INTO
          project (owner_id)
        VALUES
          (p_Owner_ID)
        RETURNING
          project.id INTO p_Project_ID;
      END;
    ELSE
      p_Project_ID := NULL;
    END IF;
  END CREATE_PROJECT;

首先,DVO充满了所有者ID,然后以DVO作为参数调用DAO,并且在调用之后,DVO包含新创建的项目的值。