Cayenne User Documentation
DataObjects Example

As discussed in DataContext chapter, any changes made to the DataObjects via "set*" methods are synchronized with the database by calling `DataContext.commitChanges`. Here is an example showing how the `Painting` object is fetched, modified and saved back. The following modifications are performed: the price of the first retrieved painting is doubled, a new painting is added that belongs to the same artist as the painting fetched before:

    import java.math.BigDecimal;
    import java.util.List;
    import org.apache.cayenne.access.DataContext;
    import org.apache.cayenne.query.SelectQuery;
    import org.apache.cayenne.exp.Expression;
    import org.apache.cayenne.exp.ExpressionFactory;
    import org.apache.art.Painting;
    import org.apache.art.Artist;
    ...

    // assume this exists and initialized
    DataContext ctxt;
    ...
    Expression e =
      ExpressionFactory.greaterExp("estimatedPrice",
                            new BigDecimal(100000.0));
    SelectQuery q = new SelectQuery(Painting.class, e);
    List realExpensiveArt = ctxt.performQuery(q);

    if(realExpensiveArt.size() > 0) {
      Painting firstPainting = (Painting)realExpensiveArt.get(0);

      // double the price
      double oldPrice = firstPainting.getEstimatedPrice().doubleValue();
      firstPainting.setEstimatedPrice(new BigDecimal(oldPrice * 2.00));

      // create new painting and register it with DataContext
      // "Painting" string is a name of ObjEntity in the DataMap
      Painting newPainting = (Painting)ctxt.newObject(Painting.class);
      newPainting.setPaintingTitle("Sunset as it is");

      // price it as unreasonable as other paintings
      newPainting.setEstimatedPrice(new BigDecimal(5000000.0));

      // get artist via relationship
      Artist artist = firstPainting.getToArtist();

      // assign new painting to an artist
      artist.addToPaintingArray(newPainting);

      // save all the changes we've made so far
      ctxt.commitChanges();
    }
    ...

If SQL tracing is turned on, and depending on the preexisting data in the database, the following SQL statements might be printed to console during the commit phase:

    [main 12-22 15:50:19] QueryLogger: --- will run 2 queries.
    [main 12-22 15:50:19] QueryLogger: INSERT INTO PAINTING (PAINTING_ID, PAINTING_TITLE, ESTIMATED_PRICE,
     ARTIST_ID) VALUES (?, ?, ?, ?) [params: 200, 'Sunset as it is', 5000000, 10]
    [main 12-22 15:50:19] QueryLogger: === updated 1 row.
    [main 12-22 15:50:19] QueryLogger: UPDATE PAINTING SET ESTIMATED_PRICE = ? WHERE PAINTING_ID = ?
     [params: 2000000, 34]
    [main 12-22 15:50:19] QueryLogger: === updated 1 row.
    [main 12-22 15:50:19] QueryLogger: +++ transaction committed.

.
Copyright ©2001-2006 Apache Software Foundation