반응형
반환 매개 변수를 사용하여 최대 절전 모드에서 오라클 함수를 호출하는 방법은 무엇입니까?
내 질문은 하이버네이트를 통해 PL/SQL 함수의 반환 값을 얻는 것과 매우 유사합니다.
나는 내부적으로 몇 가지 수정을 하는 기능이 있고 그것은 값을 반환합니다.
원래의 아이디어는 다음과 같은 것을 하는 것이었습니다.
protected Integer checkXXX(Long id, Long transId)
throws Exception {
final String sql = "SELECT MYSCHEMA.MYFUNC(" + id + ", "
+ transId + ") FROM DUAL";
final BigDecimal nr = (BigDecimal) this.getHibernateTemplate()
.getSessionFactory().getCurrentSession().createSQLQuery(sql)
.uniqueResult();
return nr.intValue();
}
안타깝게도 Oracle에서는 작동하지 않습니다.이런 일을 할 때 추천하는 방법은 무엇입니까?
내 설명 내에서 선언된 변수를 추출할 수 있는 방법이 있습니까?
Hibernate Session은 에 직접 액세스할 수 있는 방법을 제공합니다. 그런 다음 다음 기능을 만들어 실행할 수 있습니다.
session.doWork(new Work() {
public void execute(Connection connection) throws SQLException {
CallableStatement call = connection.prepareCall("{ ? = call MYSCHEMA.MYFUNC(?,?) }");
call.registerOutParameter( 1, Types.INTEGER ); // or whatever it is
call.setLong(2, id);
call.setLong(3, transId);
call.execute();
int result = call.getInt(1); // propagate this back to enclosing class
}
});
다음과 같은 옵션이 있습니다.
와 함께
@NamedNativeQuery
:@org.hibernate.annotations.NamedNativeQuery( name = "fn_my_func", query = "{ ? = call MYSCHEMA.MYFUNC(?, ?) }", callable = true, resultClass = Integer.class ) Integer result = (Integer) entityManager.createNamedQuery("fn_my_func") .setParameter(1, 1) .setParameter(2, 1) .getSingleResult();
JDBC API 사용 시:
Session session = entityManager.unwrap( Session.class ); final AtomicReference<Integer> result = new AtomicReference<>(); session.doWork( connection -> { try (CallableStatement function = connection .prepareCall( "{ ? = call MYSCHEMA.MYFUNC(?, ?) }" ) ) { function.registerOutParameter( 1, Types.INTEGER ); function.setInt( 2, 1 ); function.setInt( 3, 1 ); function.execute(); result.set( function.getInt( 1 ) ); } } );
네이티브 오라클 쿼리를 사용하는 경우
Integer result = (Integer) entityManager.createNativeQuery( "SELECT MYSCHEMA.MYFUNC(:postId, :transId) FROM DUAL") .setParameter("postId", 1) .setParameter("transId", 1) .getSingleResult();
예, out 매개 변수를 사용해야 합니다.doWork() 방법을 사용하면 다음과 같은 작업을 수행할 수 있습니다.
session.doWork(new Work() {
public void execute(Connection conn) {
CallableStatement stmt = conn.prepareCall("? = call <some function name>(?)");
stmt.registerOutParameter(1, OracleTypes.INTEGER);
stmt.setInt(2, <some value>);
stmt.execute();
Integer outputValue = stmt.getInt(1);
// And then you'd do something with this outputValue
}
});
대체 코드 :)
당신이 결과를 지시하고 싶다면 아래 코드를 사용할 수 있습니다.
int result = session.doReturningWork(new ReturningWork<Integer>() {
@Override
public Integer execute(Connection connection) throws SQLException {
CallableStatement call = connection.prepareCall("{ ? = call MYSCHEMA.MYFUNC(?,?) }");
call.registerOutParameter( 1, Types.INTEGER ); // or whatever it is
call.setLong(2, id);
call.setLong(3, transId);
call.execute();
return call.getInt(1); // propagate this back to enclosing class
}
});
http://keyurj.blogspot.com.tr/2012/12/dowork-in-hibernate.html
public static void getThroHibConnTest() throws Exception {
logger.debug("UsersActiion.getThroHibConnTest() | BEG ");
Transaction tx = null;
Connection conn = null;
CallableStatement cs = null;
Session session = HibernateUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
conn = session.connection();
System.out.println("Connection = "+conn);
if (cs == null)
{
cs =
conn.prepareCall("{ ?=call P_TEST.FN_GETSUM(?,?) }");
}
cs.clearParameters();
cs.registerOutParameter(1,OracleTypes.INTEGER);
cs.setInt(2,1);
cs.setInt(3,2);
cs.execute();
int retInt=cs.getInt(1);
tx.commit();
}catch (Exception ex) {
logger.error("UsersActiion.getThroHibConnTest() | ERROR | " , ex);
if (tx != null && tx.isActive()) {
try {
// Second try catch as the rollback could fail as well
tx.rollback();
} catch (HibernateException e1) {
logger.debug("Error rolling back transaction");
}
// throw again the first exception
throw ex;
}
}finally{
try {
if (cs != null) {
cs.close();
cs = null;
}
if(conn!=null)conn.close();
} catch (Exception ex){;}
}
logger.debug("UsersActiion.getThroHibConnTest() | END ");
}
언급URL : https://stackoverflow.com/questions/1703351/how-to-call-an-oracle-function-from-hibernate-with-a-return-parameter
반응형
'programing' 카테고리의 다른 글
당기기 위한 깃 후크가 있습니까? (0) | 2023.06.27 |
---|---|
트리거 본문에서 동일한 테이블에 대한 다른 삭제를 포함하는 삭제 후 트리거를 작성하는 방법은 무엇입니까? (0) | 2023.06.27 |
새 스레드에서 간단한 코드를 실행하려면 어떻게 해야 합니까? (0) | 2023.06.27 |
왜 글로벌 변수는 사악한가요? (0) | 2023.06.27 |
유형 스크립트에서 값으로 지도를 "필터링"할 수 있습니까? (0) | 2023.06.27 |