【发布时间】:2014-09-07 02:17:45
【问题描述】:
我正在使用 hibernate 4.2.6 和 PostgreSQL 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);
相应的行将添加到表中。为什么休眠不起作用,但使用 JDBC 的本机查询起作用?
【问题讨论】:
-
你的
createSQLQuery方法在做什么? -
@BheshGurung 是 hibernate 方法。我认为这个方法执行原生查询。
-
它应该类似于
session.createSQLQuery(sql).executeUpdate()。这就是我问的原因,您发布的代码中可能缺少某些内容。
标签: java sql hibernate postgresql jdbc