A Groovy way to use Cayenne on the fly...

From: Jonathan Carlson (Jonathan.Carlso..atun.com)
Date: Fri Mar 03 2006 - 16:36:57 EST

  • Next message: Jonathan Carlson: "A Groovier way to use Cayenne on the fly..."

    For those who wish to quickly modify some data or write a quick Groovy
    report using Cayenne data, I though I'd share this with you.

    The code is rather verbose, but it doesn't have to be that way if I (or
    someone) ever creates a DynamicConfiguration class to hide all the
    dynamic datamap generation logic. Entities, properties, and
    relationships are all inferred from the available JDBC information, like
    table names, columns, and foreign keys (Hat tip to Michael Shengaout's
    and Andrus' DbLoader class).

    If this script gets mangled by the e-mail system, let me know and I'd
    be happy to attach a clean one.

    import org.objectstyle.cayenne.exp.Expression;
    import org.objectstyle.cayenne.exp.ExpressionFactory;
    import org.objectstyle.cayenne.query.SelectQuery;
    import org.objectstyle.cayenne.CayenneDataObject;
    import org.objectstyle.cayenne.dba.AutoAdapter;
    import org.objectstyle.cayenne.conn.PoolManager;
    import org.objectstyle.cayenne.access.DataNode;
    import org.objectstyle.cayenne.access.DataDomain;
    import org.objectstyle.cayenne.access.DataContext;
    import org.objectstyle.cayenne.access.DbLoader;
    import org.objectstyle.cayenne.conf.Configuration;
    import org.objectstyle.cayenne.conf.DefaultConfiguration;
    import org.objectstyle.cayenne.map.DataMap;
    import org.objectstyle.cayenne.query.SelectQuery;

    import javax.sql.DataSource;
    import groovy.sql.Sql;

    import groovy.ui.Console;

    def dclass="oracle.jdbc.driver.OracleDriver"
    def url="jdbc:oracle:thin:10.1.1.1:MYSID"
    def user="MyUser"
    def pw="MyPassword";
    def schema="MySchema"

    // create DataSource (from the connection data that users enter via
    UI?)
    DataSource dataSource = new PoolManager(dclass, url, 1, 5, user, pw)

    // get DataMap via DbLoader
    DbLoader dbLoader =
        new DbLoader(dataSource.getConnection(), new
    AutoAdapter(dataSource), null);
    dbLoader.setGenericClassName("org.objectstyle.cayenne.CayenneDataObject");

    DataMap dataMap =
        dbLoader.loadDataMapFromDB(schema, "KOLC%", new DataMap());

    // assemble stack
    DataNode dataNode = new DataNode("DynamicNode");
    dataNode.setAdapter(new AutoAdapter(dataSource));
    dataNode.setDataSource(dataSource);
    dataNode.addDataMap(dataMap);

    DataDomain dataDomain = new DataDomain("DynamicDomain");
    dataDomain.addNode(dataNode);
    DataContext dataContext = dataDomain.createDataContext();

    println "Number of entities found:
    ${dataContext.entityResolver.dbEntities.size()}"

    /***************************
    // Starts a console so you can try some dynamic queries
    println 'Starting Console'
    println 'Bound variables: dataContext, dataMap'
    def console = new Console()
    console.shell.setVariable("dataContext", dataContext)
    console.shell.setVariable("dataMap", dataMap)
    console.run()
    return 1
    ****************************/

    /******************************************
    // Code to print out certain objEntities and their attributes
    def objEntities = dataContext.entityResolver.objEntities.findAll{ e ->
    e.name.contains('User') || e.name.contains('Role') }
    objEntities.each { e ->
      println "${e.name} ${e.dbEntityName} ${e.className} $e"
      println " Attributes:"
      e.attributes.each { attr -> println " ${attr.name}
    ${attr.type}" }
      println " Relationships:"
      e.relationships.each { rel -> println " ${rel.name}
    ${rel.targetEntityName}" }
    }
    *******************************************/

    /**
     * This class will be used to add the get(propertyName) method to
     * all CayenneDataObject instances so we can access
     * persistent properties in a Groovy way (using the dot notation).
     */
    class CayenneDataObjectCategory {
      static Object get(CayenneDataObject dataObject, String propertyName)
    {
        return dataObject.readProperty(propertyName);
      }
    }

    // Print out the roles for a set of users...
    // The use(...) below adds get(propertyName) to all CayenneDataObject
    // instances used inside of the closure.
    use (CayenneDataObjectCategory)
    {
      // I don't think it would be too hard to create a Groovy Cayenne
    query builder
      // to reduce the syntax needed for creating a query....
      SelectQuery query = new SelectQuery("Users") // Users is the entity
    name
      def qual = ExpressionFactory.likeIgnoreCaseExp("userLogin",
    "jacarl%")
      query.setQualifier(qual)
      dataContext.performQuery(query).each
      { kolcUser ->
        println " ${kolcUser.userName} has these roles:"
        kolcUser.kolcUserRolesArray.each
        { kolcUserRole ->
          kolcUserRole.toKolcRoles.each
          { kolcRole ->
            println " Role: ${kolcRole.roleCode} ${kolcRole.roleName}
    ${kolcRole.roleDescr}"
          }
        }
      }
    }

    ______________________________________________________________________
    This email and any files transmitted with it are confidential and
    intended solely for the use of the individual or entity to whom they
    are addressed. If you have received this email in error please notify
    the system manager.

    Katun Corporation -- www.katun.com
    _____________________________________________________________________



    This archive was generated by hypermail 2.0.0 : Fri Mar 03 2006 - 16:37:30 EST