Java 使用hibernate执行本机sql

Java 使用hibernate执行本机sql,java,sql,hibernate,postgresql,jdbc,Java,Sql,Hibernate,Postgresql,Jdbc,我正在使用hibernate4.2.6和postgresql9.1 我一直在尝试用hibernate执行sql查询。我写过: Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);

我正在使用
hibernate4.2.6
postgresql9.1
我一直在尝试用hibernate执行sql查询。我写过:

Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
createSQLQuery(sql);//has no effect. Query doesn't execute.
session.getTransaction().commit();
session.close();
此查询不在数据库中执行。但是如果我写

String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);", product.getName(), product.getCost());
Properties connectionProps = new Properties();
connectionProps.put("user", "postgres");
connectionProps.put("password", "123");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/solid",connectionProps);
conn.createStatement().execute(sql);
相应的行将添加到表中。为什么hibernate不工作,而JDBC工作的本机查询?

这应该会帮助您

Session session = Hibernate.util.HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String sql = String.format("INSERT INTO products (name,cost) VALUES('%s',%s);",product.getName(), product.getCost());
session.createSQLQuery(sql).executeUpdate();
session.getTransaction().commit();
session.close();

最好使用PreparedStatement(您不想让位于SQL注入)


另一个可能影响你(就像影响我一样)的问题是:

您想运行本机查询,但无法在生产代码中运行?如果应用程序使用的数据库用户与架构所有者不同,请注意。在这种情况下,您可能需要将模式前缀添加到引用的表中,以使其正常工作

在我的示例中,我使用的是实体管理器,而不是会话:

String sql = "select id from some_table";
Query query = em.createNativeQuery(sql);
List<Long> results = query.getResultList();
将Hibernate设置为所有表的前缀

<prop key="hibernate.default_schema">dba</prop>
dba

显然不会影响本机查询。

适合我的解决方案如下:

public List<T> queryNativeExecute(String query) throws CustomException {
        List<T> result =null;
        Session session =null;
        Transaction transaction=null; 
        try{
            session = HibernateUtil.getSessionJavaConfigFactory().openSession();
            transaction = session.beginTransaction();
            session.createNativeQuery(query).executeUpdate();
            transaction.commit();
        }catch(Exception exception){
            result=null;
            if (transaction !=null && transaction.isActive()){
                transaction.rollback();
            }
            throw new CustomException(exception.getMessage(),exception,error.ErrorCode.DATABASE_TABLE,this.getClass().getSimpleName());
        }finally{
            if (session !=null){
                session.close();    
            }
        }

        return result;
    }   
公共列表查询活动执行(字符串查询)引发CustomException{
列表结果=空;
会话=空;
事务=空;
试一试{
session=HibernateUtil.getSessionJavaConfigFactory().openSession();
事务=session.beginTransaction();
createNativeQuery(query.executeUpdate();
commit();
}捕获(异常){
结果=空;
if(transaction!=null&&transaction.isActive(){
transaction.rollback();
}
抛出新的CustomException(exception.getMessage(),exception,error.ErrorCode.DATABASE_表,this.getClass().getSimpleName());
}最后{
if(会话!=null){
session.close();
}
}
返回结果;
}   

你的
createSQLQuery
方法在做什么?@BheshGurung这是hibernate方法。我认为该方法执行本机查询。它应该类似于
session.createSQLQuery(sql.executeUpdate()
。这就是我问的原因,可能是您发布的代码中缺少了一些内容。我假设
cost
是一个数字列,数字不需要单引号。为什么要使用%s than.@a_horse_with_no_name是的,cost是整数。如果它不起作用,请发布createSQLQuery()方法的内容。
createSQLQuery()
自hibernate 5.2以来已被弃用。现在您应该改用
createNativeQuery()
<prop key="hibernate.default_schema">dba</prop>
public List<T> queryNativeExecute(String query) throws CustomException {
        List<T> result =null;
        Session session =null;
        Transaction transaction=null; 
        try{
            session = HibernateUtil.getSessionJavaConfigFactory().openSession();
            transaction = session.beginTransaction();
            session.createNativeQuery(query).executeUpdate();
            transaction.commit();
        }catch(Exception exception){
            result=null;
            if (transaction !=null && transaction.isActive()){
                transaction.rollback();
            }
            throw new CustomException(exception.getMessage(),exception,error.ErrorCode.DATABASE_TABLE,this.getClass().getSimpleName());
        }finally{
            if (session !=null){
                session.close();    
            }
        }

        return result;
    }