我正在使用 Play 框架 1.2.5,我想通过创建存储过程并使用它们来优化我的 SQL 查询,但我不知道该怎么做。
要通过Java代码创建存储过程我应该怎么做?另外,我应该在 @OnApplicationStart 作业中执行此操作,以便确保在应用程序启动时创建并存储过程吗?
之后,我该如何使用我的存储过程?使用哪个功能?如何将参数传递给我的程序?我怎样才能检索我的程序的结果? (通常结果将是一个 SELECT 查询)最后,是否可以将我的过程的结果绑定(bind)到 Play Framework 中的模型?
我有很多问题,但我对 Play 框架和 JPA 的存储过程不熟悉,我想确保我正确使用它们
感谢您的帮助
最佳答案
我不知道你应该如何创建它们。也许 OnApplicationStart 方法正是您所需要的。在我的环境中,这些程序已经就位。我们只需使用 Play 来调用它们。要调用存储过程,您应该查看 Work
接口(interface)。通过实现这个,您可以在数据库中执行语句。
我们创建了一个基本的 OracleProcedure 类:
public class CallOracleProcedure implements Work {
private String anonymousPLSQL;
private String[] parameters;
public CallOracleProcedure(String anonymousPLSQL, String[] parameters) {
this.anonymousPLSQL = anonymousPLSQL;
this.parameters = parameters.clone();
}
/**
* Create a JDBC PreparedStatement and then execute the anonymous
* PL/SQL procedure.
*/
@Override
public void execute(Connection connection) {
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("begin " + anonymousPLSQL + "; end;");
if (parameters != null) {
int i = 1;
for (String param : parameters) {
statement.setString(i++, param);
}
}
statement.executeUpdate();
} catch (SQLException e) {
Logger.error("Error performing anonymous pl/sql statement: '%s', with parameters: '%s' - catched error '%s'", anonymousPLSQL, parameters, e);
} finally {
if (statement != null) {
try {
statement.close();
} catch (Exception e) {
Logger.error("Error closing statement: %s", e);
}
}
}
}
}
对于每个特定的存储过程,您可以扩展此类并通过 super()
将名称和参数传递给构造函数:
public class StoredProcedureCall extends CallOracleProcedure {
public StoredProcedureCall(String param) {
super("package.storedprocedure(?)", new String[] { orgname });
}
}
在您的代码中,您可以这样调用它:
StoredProcedureCall procedure = new StoredProcedureCall("your parameter");
session.doWork(procedure);
如果您需要调用过程并检索返回值,您可以在 execute()
方法中使用 CallableStatement
:
public class ProcedureWithReturnValue implements Work {
private final String parameter;
private String returnValue = null;
public ProcedureWithReturnValue (final String parameter) {
this.parameter = parameter;
}
@Override
public void execute(Connection connection) {
CallableStatement statement = null;
try {
statement = connection.prepareCall("begin ? := package.procedure(?); end;");
statement.registerOutParameter(1, OracleTypes.VARCHAR);
statement.setString(2, parameter);
statement.execute();
returnValue = statement.getString(1);
} catch (SQLException e) {
Logger.error("Error getting return value - catched error '%s'", e);
}
}
public String getReturnValue() {
return returnValue;
}
}
关于jpa - 通过 Play Framework 和 JPA 创建和使用存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15246245/