Execute native sql with hibernate

后端 未结 4 1406
轻奢々
轻奢々 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();
    
    0 讨论(0)
  • 2021-01-02 13:40

    The solution that work for me is the following:

    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;
        }   
    
    0 讨论(0)
  • 2021-01-02 13:54

    This should help you.

    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();
    
    0 讨论(0)
  • 2021-01-02 13:55

    Another issue that might hit you (like it hit me) is this:

    You want to run a native query, but can't get it to work in your production code? Pay attention if you are using a different database user for the application than the schema owner. In that case you may have to add the schema prefix to the referenced tables in order to make it work.

    In my example I am using an entity manager instead of the session:

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

    if some_table is owned by e.g. dba while the application is running as user, you will need to modify the query to:

    String sql = "select id from dba.some_table";
    

    Having Hibernate set to prefix all tables with

    <prop key="hibernate.default_schema">dba</prop>
    

    does apparently NOT affect native queries.

    0 讨论(0)
提交回复
热议问题