Execute native sql with hibernate

后端 未结 4 1436
轻奢々
轻奢々 2021-01-02 13:35

I\'m using hibernate 4.2.6 and PostgreSQL 9.1 I\'ve been trying to execute sql query with hibernate. I\'ve written:

Session session         


        
4条回答
  •  梦谈多话
    2021-01-02 13:38

    Its always better to use PreparedStatement (You dont want to give way to SQL Injections).

    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();
    

提交回复
热议问题