[英]Execute native sql with hibernate
我正在使用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();
使用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<Long> results = query.getResultList();
如果some_table在應用程序作為用戶運行時由例如dba擁有,則需要將查詢修改為:
String sql = "select id from dba.some_table";
將Hibernate設置為所有表的前綴
<prop key="hibernate.default_schema">dba</prop>
顯然不會影響本機查詢。
對我有用的解決方案如下:
public List<T> queryNativeExecute(String query) throws CustomException {
List<T> result =null;
Session session =null;
Transaction transaction=null;
try{
session = HibernateUtil.getSessionJavaConfigFactory().openSession();
transaction = session.beginTransaction();
session.createNativeQuery(query).executeUpdate();
transaction.commit();
}catch(Exception exception){
result=null;
if (transaction !=null && transaction.isActive()){
transaction.rollback();
}
throw new CustomException(exception.getMessage(),exception,error.ErrorCode.DATABASE_TABLE,this.getClass().getSimpleName());
}finally{
if (session !=null){
session.close();
}
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.