用hibernate执行本机sql [英] Execute native sql with hibernate

查看:124
本文介绍了用hibernate执行本机sql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 hibernate 4.2.6 PostgreSQL 9.1
我一直在尝试用hibernate执行sql查询。我写过:

I'm using hibernate 4.2.6 and PostgreSQL 9.1 I've been trying to execute sql query with hibernate. I've written:

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();

此查询不在DB中执行。但如果我写了

This query does not executed in DB. But if I write

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的原生查询是否有效?

corresponding row will add to table. Why hibernate doesn't work, but native query wth JDBC works?

推荐答案

这应该可以帮到你。

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();

这篇关于用hibernate执行本机sql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆