我正在使用,hibernate 4.2.6并且PostgreSQL 9.1 一直在尝试使用hibernate模式执行sql查询。我写过:
hibernate 4.2.6
PostgreSQL 9.1
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();