当前位置: 代码迷 >> Java Web开发 >> hibernate和jdbc有关问题
  详细解决方案

hibernate和jdbc有关问题

热度:323   发布时间:2016-04-17 17:22:29.0
hibernate和jdbc问题
使用hibernate框架,oracle数据库,属性和列是通过.hbm.xml配置文件匹配的,hql语句操作数据库。现在问题是有些语句用不上,比如内关联查询就会报错。
想问一下能不能在hibernate框架上使用jdbc连接数据库用SQL语句操作数据库?意思是想用hql时能用hql,想用sql时能用sql,求方法或例子

------解决方案--------------------
自己封装个DBUtil类、在封装成各种操作的函数。在自己调用相应的函数就行了。
Java code
     /**     * 传入一个Object ,如User,将保存user相关的信息.     * @param obj     * @return 保存对象的id     * @throws HibernateException 数据库操作异常     */    static Serializable create(Object obj)    {        Session session = null;        try        {            //如果传入的对象为null,或者不是合法的DTO。            if (null == obj || !isValidClass(obj.getClass()))            {                throw new IllegalArgumentException(                    "argument is null,or class is invalid!");            }            else            {                // 开启连接                session = HibernateUtil.currentSession();                                // 开启事务                Transaction tx = session.beginTransaction();                Serializable id = session.save(obj);                tx.commit();                                return id;            }        }        catch (HibernateException ex)        {            LOG.error("create failed, obj=" + obj.toString(), ex);            throw ex;        }        finally        {            HibernateUtil.closeSession(session);        }    }    /**     *  执行sql语句     */    static void updateBySQL(String sql) throws SQLException    {        if (null == sql)        {            return;        }        Session session = null;        Connection conn = null;        Statement ste = null;        try        {            session = HibernateUtil.currentSession();            Transaction tx = session.beginTransaction();            conn = session.connection();            ste = conn.createStatement();            ste.executeUpdate(sql);            tx.commit();        }        catch (SQLException ex)        {            LOG.error("updateBySQL failed, sql=" + sql, ex);            throw ex;        }        catch (HibernateException ex)        {            LOG.error("updateBySQL failed, sql=" + sql, ex);            throw ex;        }        finally        {            if (ste != null)            {                ste.close();            }                        if (conn != null)            {                conn.close();            }                        HibernateUtil.closeSession(session);        }    }
------解决方案--------------------
Hibernate支持原生SQL
getSession().createSQLQuery(sql)
------解决方案--------------------
探讨

Hibernate支持原生SQL
getSession().createSQLQuery(sql)
  相关解决方案