用hibernate执行本机sql

我正在使用hibernate 4.2.6PostgreSQL 9.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(); 

此查询不在DB中执行。 但是如果我写的话

 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 = "INSERT INTO products (name,cost) VALUES (?,?)"; Session sess = Hibernate.util.HibernateUtil.getSessionFactory().openSession(); Connection con = sess.connection(); PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, product.getName()); pstmt.setInt(2, product.getCost()); pstmt.executeUpdate(); con.commit(); pstmt.close(); 

可能会打击你的另一个问题(比如打击我)是这样的:

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

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

 String sql = "select id from some_table"; Query query = em.createNativeQuery(sql); List results = query.getResultList(); 

如果some_table在应用程序作为用户运行时由例如dba拥有,则需要将查询修改为:

 String sql = "select id from dba.some_table"; 

将Hibernate设置为所有表的前缀

 dba 

显然不会影响本机查询。