问题
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