Calling a DB function from Hibernate

狂风中的少年 提交于 2019-12-25 07:56:38

问题


I am trying to build a job that reindexes our DB every Friday. We are using hibernate and everything I have tried so far has failed. Is there a way to execute SQL managament commands using hibernate? Such as:

    Session session = helper.getSession();
    session.createQuery("DBCCREINDEX(User)").executeUpdate();

Or is there a better way to reindex within Hibernate?


回答1:


The examples referenced below are for Oracle PL/SQL but conceptually it's the same for other databases. By "build a job" and "execute SQL managament commands" I assume you'll have some sort of function stored in the database that you need to call.

https://stackoverflow.com/a/2943733/131929 has a lengthy explanation but it boils down to

CallableStatement statement = session.connection().prepareCall(
        "{ ? = call name_of_your_function(?) }");

which allows you to work directly with a Connection and a PreparedStatement/CallableStatement.

https://stackoverflow.com/a/1703398/131929 is essentially the same but it makes use of Session#doWork

session.doWork(new Work() {
  public void execute(Connection connection) throws SQLException {
    CallableStatement call = connection.prepareCall("{ ? = call name_of_your_function(?) }");

Note that in both examples it was required to process the function's return value in the Java code which may or may not be the case with you.




回答2:


Session.createQuery() expects a HQL query. If you want to execute SQL, use Session.createSQLQuery().




回答3:


We ended up working our way after many errors up to the solution below. The prepared statement is a stored procedure to reindex created in MSSQL SSMS.

    private void reindex() {
        Session session = helper.getSession();
        PreparedStatement ps;
        session.doWork(new Work() {
        public void execute(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement("reindexTable");
            ps.execute();
        }
    });
}

This seems to have given the desired result and executes...however we just have to solve a timeout issue now.




回答4:


Try this code -

private void reindex() {
    Session session = helper.getSession();
    PreparedStatement ps;
        session.doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement("reindexTable");
            ps.execute();
        }
    });
}


来源:https://stackoverflow.com/questions/16902514/calling-a-db-function-from-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!