如何使用HibernateDaoSupport获取数据库中的表列表?

时间:2017-06-07 06:16:37

标签: java spring hibernate dao

我在这里添加了我的代码。当我尝试获取表的列表时,在try块中出现问题。

数据库是MySql
例外情况是: java.lang.IllegalArgumentException:要遍历的节点不能为空!

public class DBOptimizationDAO extends HibernateDaoSupport {

private static final Log log  = LogFactory.getLog(DBOptimizationDAO.class);

public void optimizeAdapter(String year)
{
    List<com.ecw.adapterservice.beans.TransactionInbound> transactionInboundList = null;
    StringBuilder queries = new StringBuilder();
    try {       
        transactionInboundList = (List<com.ecw.adapterservice.beans.TransactionInbound>)super.getHibernateTemplate().find("from TransactionInbound where inboundTimestamp < '" + year+ "-01-01'order by 1 desc limit 2");

        //  Check if archive table exist or not
        List<Object> inboundObj = getHibernateTemplate().find("SHOW TABLES LIKE transaction_outbound");
        List<Object> outboundObj = getHibernateTemplate().find("SHOW TABLES LIKE 'transaction_outbound_archive'");

1 个答案:

答案 0 :(得分:0)

HibernateTemplate::find期望字符串参数中的HQL查询,并且您正在传递本机语句。您可以使用HibernateTemplate::getSession返回的Session对象执行本机内容(查询,语句等)。要传递原生选择查询,您可以使用Session::createSQLQuery

但是你真的想依靠数据库特定的代码来做这件事吗?使用DatabaseMetaData::getTables更优雅的方式。见this answer。您可以获取DatabaseMetaData from a callback method of your HibernateTemplate的实例。

试试这个:

        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        if(!session instaceof SessionImpl){
                    //handle this, maybe throw an exception
                }
        else {
            Connection con = (SessionImpl)session.connection();
            ...
        }