Hi everyone....

i'm tryng to write a translator from implementing select count(*) from a Select Query with an Expression built at runtime via ExpressionFactory.

In cayenne 2.0 i was using something like:

static class CountTranslator extends SelectTranslator {

        @Override

        public String createSqlString() throws Exception {

            String sql = super.createSqlString();

            int index = sql.indexOf(" FROM ");

            return "SELECT COUNT(*)" + sql.substring(index);

        }

    }

    public int count(SelectQuery query,

            DataNode node) {

        CountTranslator translator = new CountTranslator();

        translator.setQuery(query);

        translator.setAdapter(node.getAdapter());

        
translator.setEntityResolver(DataContext.getThreadDataContext().getEntityResolver());

        Connection con = null;

        PreparedStatement stmt = null;

        try {

            con = node.getDataSource().getConnection();

            translator.setConnection(con);

            stmt = translator.createStatement();

            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {

                return rs.getInt(1);

            }

            throw new org.apache.cayenne.CayenneRuntimeException("Count query 
returned no result");

        } catch (Exception e) {

            throw new CayenneRuntimeException("Cannot count", e);

        } finally {

            try {

                if (stmt != null) {

                    stmt.close();

                }

                if (con != null) {

                    con.close();

                }

            } catch (Exception ex) {

                throw new CayenneRuntimeException("Cannot close connection", 
ex);

            }

        }

    }



the only thing i nedeed was to get the current connection from the context which i did using something like

    
DataContext.getThreadDataContext().getParentDataDomain().getDataNodes().iterator().next()


but now in Cayenne 3.1 this method seems to be invalid 'cause i cannot get ParentDataDomain from ObjectContext.
Besides that this works only if have a datanode set for the domain.
Is there any other or better way to proceed?

Thanks, Marco



Reply via email to