Re: how to translate a sqlselectquery to correct object?

From: Andrus Adamchik (andru..bjectstyle.org)
Date: Sat Nov 15 2003 - 18:36:27 EST

  • Next message: Andrus Adamchik: "Re: Inheritance?"

    Hi Jeffery,

    there is a way to configure how the columns in the SqlSelectQuery are
    converted into Java classes. Here is a small example. Given a table:

    CREATE TABLE date_test (date_col DATE NULL, id INT NOT NULL, PRIMARY
    KEY (id))

    we can run the following query, ensuring that the date is returned as
    java.sql.Date:

            SqlSelectQuery rawQuery =
                 new SqlSelectQuery(
                     DateTest.class,
                     "SELECT t0.date_col, t0.id FROM date_test t0");

             // configure SQL query to do the right conversions:
             ObjEntity entity =
    context.getEntityResolver().lookupObjEntity(DateTest.class);
             ObjAttribute[] descriptors = new ObjAttribute[2];

             // use this attribute from entity for the first column
             descriptors[0] = (ObjAttribute) entity.getAttribute("dateCol");

             // create a dummy second attribute, since it does not exist in
    the entity:
             descriptors[1] = new ObjAttribute("dummy");
             descriptors[1].setType(Integer.class.getName());

             // set descriptors
             rawQuery.setObjDescriptors(descriptors);

             // run query
             List rawDates = context.performQuery(rawQuery);

    I hope this helps. I am wondering though why is it a problem using
    java.util.Date in your application? I personally find it easier to use
    in the code in place of both dates and timestamps.

    Andrus

    On Nov 14, 2003, at 12:35 PM, <wwlo..itao.com> wrote:
    > hi!
    > I want to get a CayenneObject using SqlSelectQuery, my source code
    > like this:
    >
    > ObjEntity ent =
    > MYDataContext.getDataContext().getEntityResolver().lookupObjEntity(enti
    > tyName);
    > SqlSelectQuery ssq = new SqlSelectQuery(ent, sql);
    > List result = MYDataContext.getDataContext().performQuery(ssq);
    > if (result.size() == 0)
    > return null;
    >
    > for (Iterator it = result.iterator(); it.hasNext();) {
    > Map m = (Map) it.next();
    > Object o =
    > MyDataContext.getDataContext().objectFromDataRow(ent, m, false);
    > }
    >
    > As myEntity have a field whose type is java.sql.Date, in the
    > returned Object o, I got a java.util.Date
    > for the corresponding field.
    > I read cayenned source, cayenne convert this using javaTypes and
    > dbAttributes in the ResultDescriptor
    > class, but I did not find an easy way to reach my goal.
    > Can you help me? thanks for your reading and sorry for my poor
    > english!
    >
    > Jeffery Lou
    > 2003-11-15



    This archive was generated by hypermail 2.0.0 : Sat Nov 15 2003 - 18:36:40 EST