我正在使用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);
相应的行将添加到表中.为什么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();