简体   繁体   English

H2 数据库中的存储过程

[英]Stored Procedure in H2 Database

I am new to database and recently started writing test cases for H2 database.我是数据库新手,最近开始为 H2 数据库编写测试用例。 I want to know how to test a stored procedure in Eclipse.我想知道如何在 Eclipse 中测试存储过程。 I have seen the following:我看到了以下内容:

http://www.h2database.com/html/features.html#user_defined_functions http://www.h2database.com/html/features.html#user_defined_functions

How to CREATE PROCEDURE in H2 如何在 H2 中创建过程

The sample code given in the h2database link, h2database 链接中给出的示例代码,

"CREATE ALIAS NEXT_PRIME AS $$
String nextPrime(String value) {
    return new BigInteger(value).nextProbablePrime().toString();
}
$$;
" 
  • Where should this be declared?and how to run it?应该在哪里声明?如何运行?

PS - I have the H2 JAR file and am testing it. PS - 我有 H2 JAR 文件并正在测试它。

If someone can tell me how to write a simple stored procedure in Java for H2, it would be of great help.如果有人能告诉我如何用 Java 为 H2 编写一个简单的存储过程,那将有很大帮助。

Also is there any equivalent of the following in H2? H2 中是否也有以下等价物?

"begin dbms_output"? “开始 dbms_output”?

Thanks.谢谢。

There is no stored procedure and sql userdefined function in H2 database instead of that we use java methods and create a alias to refer that.We can call that methods using alias. H2 数据库中没有存储过程和 sql 用户定义函数,而是我们使用 java 方法并创建别名来引用它。我们可以使用别名调用该方法。

Below is a simple example:**下面是一个简单的例子:**

DROP ALIAS IF EXISTS MYFUNCTION;
CREATE ALIAS MYFUNCTION AS $$
String getTableContent(java.sql.Connection con) throws Exception {
    String resultValue=null;
    java.sql.ResultSet rs = con.createStatement().executeQuery(
    " SELECT * FROM TABLE_NAME");
       while(rs.next())
       {
        resultValue=rs.getString(1);
       }
    return resultValue;
}
$$;

You may have overlooked the examples in src/test/org/h2/samples/Function.java .您可能忽略了src/test/org/h2/samples/Function.java中的示例。 Here's a related example:这是一个相关的例子:

Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("CREATE ALIAS getVersion FOR \"org.h2.engine.Constants.getVersion\"");
ResultSet rs;
rs = st.executeQuery("CALL getVersion()");
if (rs.next()) System.out.println("Version: " + rs.getString(1));

Console: Version: 1.4.191控制台: Version: 1.4.191

Addendum: The feature is not limited to functions;附录:该功能不限于功能; aliased methods can execute arbitrary Java code .别名方法可以执行任意Java 代码 For example, the query() method defined in Function.java may be aliased and called as shown below:例如, Function.java中定义的query()方法可能会被别名调用,如下所示:

Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("CREATE ALIAS query FOR \"cli.Function.query\"");
rs = st.executeQuery("CALL query('SELECT NAME FROM INFORMATION_SCHEMA.USERS')");
while (rs.next()) {
    System.out.println("User: " + rs.getString(1));
}

Console: User: SA控制台: User: SA

Note that cli.Function.query is a copy of org.h2.samples.Function.query .请注意, cli.Function.queryorg.h2.samples.Function.query的副本。

Below is the way we used to implemented in our project.下面是我们过去在项目中实现的方式。 It might be helpful:)这可能会有所帮助:)

package com.procedures;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class CRITICAL_ACTIONS {

    public static final int SAVE_ACTION(Connection connection) throws SQLException {
        try {
            Statement statement = connection.createStatement();
            return statement.executeUpdate("INSERT INTO SCHEMA1.CRITICAL_ACTIONS(COLLEAGUE_ID,JOURNEY_ID,TYPE,PRODUCT,DESCRIPTION,META_DATA,STATUS) values('12345',11111111,'ABC','Lloyds','hellow','hello','START')");
        } finally {
            //connection.close();
        }
    }

    public static final ResultSet FETCH_ACTION(Connection connection) throws SQLException {
        try {
            Statement statement = connection.createStatement();
            return statement.executeQuery("SELECT * FROM SCHEMA1.CRITICAL_ACTIONS");
        }finally {
            connection.close();
        }
    }


}

Calling H2 Java Stored-procedure in Java:-在 Java 中调用 H2 Java 存储过程:-

    jdbcTemplate.update("CREATE ALIAS SAVE_ACTION FOR \"com.procedures.CRITICAL_ACTIONS.SAVE_ACTION\"");
    jdbcTemplate.update("CREATE ALIAS FETCH_ACTION FOR \"com.procedures.CRITICAL_ACTIONS.FETCH_ACTION\"");

    jdbcTemplate.getDataSource().getConnection().createStatement().execute("call SAVE_ACTION()");

Stored procedure in H2 database is same as java methods.So write java methods and can invoke using aliases. H2数据库中的存储过程与java方法相同。所以写java方法,可以使用别名调用。

The H2 is not supporting stored procedures. H2不支持存储过程。 In place of stored procedure we can create a function which returns an output like a stored-procedures.我们可以创建一个像存储过程一样返回输出的函数来代替存储过程。 Same as we're using in registerInOut parameters.与我们在 registerInOut 参数中使用的相同。 For example, if your QueryConst looks like this:例如,如果您的 QueryConst 看起来像这样:

public static final String INSERT_EMPLOYEE = "{call INSERT_EMPLOYEE(?,?,?)}";

then,然后,

We can use schema.sql (which executes before @Test )我们可以使用schema.sql (在@Test之前执行)

DROP ALIAS IF EXISTS INSERT_EMPLOYEE;
CREATE ALIAS INSERT_EMPLOYEE FOR "com.test.EmployeeDaoImplTest.updateEmpStoredproc";

package com.test;
@ContextConfiguration(locations = { "classpath:configxmltest.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@Sql(scripts = { "classpath:schema.sql" }, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
public class EmployeeDaoImplTest {
    
    public static final String INSERT_EMPLOYEE = "{call INSERT_EMPLOYEE(?,?,?)}";


    @Autowired
    EmployeeDaoImpl employeeDaoTest;
    

and other dependencies....(if any)和其他依赖项....(如果有的话)

    @Test
    public void testUpdateEmployee() {
        ..ur logic if any input data settings
        assertEquals("Inserted Successfully", employeeDaoTest.updateEmployee(input, INSERT_EMPLOYEE));
    }

    public static ResultSet updateEmpStoredproc(String name, String w, Integer i) throws SQLException {
        SimpleResultSet rs = new SimpleResultSet();
        rs.addColumn("input", Types.VARCHAR, 255, 0);
        rs.addColumn("error", Types.VARCHAR, 255, 0);
        rs.addColumn("count", Types.INTEGER, 10, 0);
        rs.addRow(0, "Inserted Successfully");
        rs.addRow(1, 10);
        return rs;
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM