source

스프링 지속성 프레임워크를 사용하여 오라클 함수 또는 저장 프로시저를 호출하는 방법은 무엇입니까?

ittop 2023. 8. 15. 11:44
반응형

스프링 지속성 프레임워크를 사용하여 오라클 함수 또는 저장 프로시저를 호출하는 방법은 무엇입니까?

저는 제 프로젝트에 Spring persistence 프레임워크를 사용하고 있습니다.이 프레임워크에서 오라클 함수 또는 스토어드 프로시저를 호출하고 싶습니다.

제가 어떻게 이것을 성취할 수 있는지 누가 제안할 수 있습니까?

* 오라클 함수와 *저장 프로시저 모두에 대한 솔루션을 제공하십시오.

감사해요.

JdbcTemplate를 참조한다고 가정합니다.

jdbcTemplate.execute(
    new CallableStatementCreator() {
        public CallableStatement createCallableStatement(Connection con) throws SQLException{
            CallableStatement cs = con.prepareCall("{call MY_STORED_PROCEDURE(?, ?, ?)}");
            cs.setInt(1, ...); // first argument
            cs.setInt(2, ...); // second argument
            cs.setInt(3, ...); // third argument
            return cs;
        }
    },
    new CallableStatementCallback() {
        public Object doInCallableStatement(CallableStatement cs) throws SQLException{
            cs.execute();
            return null; // Whatever is returned here is returned from the jdbcTemplate.execute method
        }
    }
);

함수 호출은 거의 동일합니다.

jdbcTemplate.execute(
    new CallableStatementCreator() {
        public CallableStatement createCallableStatement(Connection con) {
            CallableStatement cs = con.prepareCall("{? = call MY_FUNCTION(?, ?, ?)}");
            cs.registerOutParameter(1, Types.INTEGER); // or whatever type your function returns.
            // Set your arguments
            cs.setInt(2, ...); // first argument
            cs.setInt(3, ...); // second argument
            cs.setInt(4, ...); // third argument
            return cs;
        }
    },
    new CallableStatementCallback {
        public Object doInCallableStatement(CallableStatement cs) {
            cs.execute();
            int result = cs.getInt(1);
            return result; // Whatever is returned here is returned from the jdbcTemplate.execute method
        }
    }
);

Spring에서 Oracle 함수를 호출하는 더 간단한 방법은 아래와 같이 StoredProcedure를 하위 분류하는 것입니다.

public class MyStoredProcedure extends StoredProcedure{
    private static final String SQL = "package.function";

    public MyStoredProcedure(DataSource ds){
        super(ds,SQL);
        declareParameter(new SqlOutParameter("param_out",Types.NUMERIC));
        declareParameter(new SqlParameter("param_in",Types.NUMERIC));
        setFunction(true);//you must set this as it distinguishes it from a sproc
        compile();
    }

    public String execute(Long rdsId){
        Map in = new HashMap();
        in.put("param_in",rdsId);
        Map out = execute(in);
        if(!out.isEmpty())
            return out.get("param_out").toString();
        else
            return null;
    }
}

그리고 이렇게 부릅니다.

@Autowired DataSource ds;
MyStoredProcedure sp = new MyStoredProcedure(ds);
String i = sp.execute(1l);

여기서 사용되는 Oracle 함수는 숫자 매개 변수만 사용하고 숫자 매개 변수를 반환합니다.

제 생각에 이것은 가장 쉬운 접근법 중 하나입니다.

public class ServRepository {

    private JdbcTemplate jdbcTemplate;
    private SimpleJdbcCall functionGetServerErrors;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        jdbcTemplate.setResultsMapCaseInsensitive(true);
        this.functionGetServerErrors = new SimpleJdbcCall(jdbcTemplate).withFunctionName("THIS_IS_YOUR_DB_FUNCTION_NAME").withSchemaName("OPTIONAL_SCHEMA_NAME");
    }

        public String callYourFunction(int parameterOne, int parameterTwo) {
            SqlParameterSource in = new MapSqlParameterSource().addValue("DB_FUNCTION_INCOMING_PARAMETER_ONE", parameterOne).addValue("DB_FUNCTION_INCOMING_PARAMETER_TWO", parameterTwo);
            return functionGetServerErrors.executeFunction(String.class, in);
        }
}

다음을 사용한 호출 기능NamedParameterJdbcTemplate:

final String query = "select MY_FUNCTION(:arg1, :arg2, :arg3) from dual";
Map<String, Object> argMap = new HashMap<>();
argMap.put("arg1", "value1");
argMap.put("arg2", 2);
argMap.put("arg3", "value3");
final String result = new NamedParameterJdbcTemplate(dataSource)
        .queryForObject(query, argMap, String.class);

다음을 사용한 호출 절차JdbcTemplate:

final String query = "call MY_PROCEDURE(?, ?, ?)";
final Object[] args = {"arg1", "arg2", "arg3"};
new JdbcTemplate(dataSource).execute(query, args, String.class);

다음을 사용한 호출 기능SimpleJdbcCall:

Map<String, Object> inParameters = new HashMap<>();
inParameters.put("arg1", 55); // arg1 value
inParameters.put("arg2", 20); // arg2 value
MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource(inParameters);
BigDecimal result = new SimpleJdbcCall(dataSource)
        .withCatalogName("MY_PACKAGE")
        .withSchemaName("MY_SCHEMA")
        .withFunctionName("MY_FUNCTION")
        .executeFunction(BigDecimal.class, mapSqlParameterSource);

다음을 사용한 호출 절차SimpleJdbcCall:

new SimpleJdbcCall(dataSource)
        .withCatalogName("MY_PACKAGE")
        .withProcedureName("MY_PROCEDURE")
        .execute("arg1", arg2);

언급URL : https://stackoverflow.com/questions/862694/how-to-call-oracle-function-or-stored-procedure-using-spring-persistence-framewo

반응형