Simple Java example to call a stored procedure in JPA / JDBC
Example 1:
public void myMethod(Lists list, Account account) {or
Query query = em.createNativeQuery("call example_procedure(?,?);");
query.setParameter(1, list.getListid()).setParameter(2,
account.getUserid());
query.executeUpdate();
}
public void myMethod(Lists list, Account account) {
em.createNativeQuery("call example_procedure(?p1,?p2);")
.setParameter("p1", list.getListid())
.setParameter("p2", account.getUserid()).executeUpdate();
}
Example 2:
// for getting the result back.Example 3:
String q = "call `i88ca`.`example_procedure2`();";
Object o = em.createNativeQuery(q).getSingleResult();
// or
List l = em.createNativeQuery(q).getResultList();
PROCEDURE `example_procedure2`()
BEGIN
select 8888;
-- or any other select statements for output.
END
@Resource(name = "db2")Example 4:
private DataSource dataSource;
public void changeAccount(Integer listid, Integer accountid) throws SQLException {
Connection conn = dataSource.getConnection();
CallableStatement cs =conn.prepareCall("call test(?,?)");
cs.setInt(2, 3);
cs.execute();
cs.close();
conn.close();
}
CallableStatement cs = conn.prepareCall("call test(?,?,?)");
cs.setInt(2, 3);
cs.registerOutParameter(3, Types.INTEGER);
cs.execute();
// Get the value of the output parameter.
int sum = cs.getInt(3);
cs.close();
conn.close();
You may want to check that:
Stored Procedures should be considered database assembly language: for use in only the most performance critical situations.
See also:
Comments
Post a Comment