Get hold of a JDBC Connection object from a Stateless Bean

后端 未结 7 1823
孤街浪徒
孤街浪徒 2020-12-09 18:43

In a Stateless Session Bean an EntityManager is injected but I would like to get hold of a Connection object in order to invoke a DB Procedure. Is

7条回答
  •  再見小時候
    2020-12-09 19:13

    In JPA2.0, if need JDBC is por DTO nomodel or entity for query more complex. Sometimes JPA is not all...

    I hope this will help you:

    Statement statement = null;
    EntityManager em = null;
    em = emf.createEntityManager();
    EntityTransaction et = em.getTransaction();
    
    if(!et.isActive()) {
        et.begin();
    }
    
    java.sql.Connection connection = em.unwrap(java.sql.Connection.class);
    
        String qquerry="SELE ...
        try {   
            statement = connection.createStatement();
            ResultSet rs =  statement.executeQuery(qquerry);                                                              
    
            if (!rs.next()) {
                return null;
            }
            else{
                wwwwas=rs.getString(4);                                 
            }         
            statement.close();
            } 
        catch (SQLException e) {
            System.out.println("\n b-03:"+e);
            throw new RuntimeException(e.getMessage(), e);
        } 
        finally {
            try {
                //  em.getTransaction().commit();
                if(connection != null )
                connection.close();
            } 
            catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
           }
        }
    

提交回复
热议问题