用hibernate执行本机sql

St.*_*rio 6 java sql postgresql hibernate jdbc

我正在使用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();
Run Code Online (Sandbox Code Playgroud)

此查询不在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);
Run Code Online (Sandbox Code Playgroud)

相应的行将添加到表中.为什么hibernate不起作用,但JDBC工作的本机查询?

Dar*_*ila 11

这应该对你有帮助.

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();
Run Code Online (Sandbox Code Playgroud)


Jp *_*ori 8

使用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();
Run Code Online (Sandbox Code Playgroud)


小智 5

另一个可能会打击您的问题(就像它打击了我)是:

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

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

String sql = "select id from some_table";
Query query = em.createNativeQuery(sql);
List<Long> results = query.getResultList();
Run Code Online (Sandbox Code Playgroud)

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

String sql = "select id from dba.some_table";
Run Code Online (Sandbox Code Playgroud)

将Hibernate设置为所有表的前缀

<prop key="hibernate.default_schema">dba</prop>
Run Code Online (Sandbox Code Playgroud)

显然不会影响本机查询。