cayenne-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] Apache Cayenne > Enumerations Example
Date Sat, 26 Jun 2010 16:09:00 GMT
<html>
<head>
    <base href="https://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/1810/9/25/_/styles/combined.css?spaceKey=CAY&amp;forWysiwyg=true"
type="text/css">
    </head>
<body style="background: white;" bgcolor="white" class="email-body">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
     <h2><s>Enumerations Example</s></h2>
     <h4>Page <b>removed</b> by             <a href="https://cwiki.apache.org/confluence/display/~andrus">Andrus
Adamchik</a>
    </h4>
     <br/>
     <div class="notificationGreySide">
         
<h3><a name="EnumerationsExample-ContributedbyMichaelGentry"></a>Contributed
by Michael Gentry</h3>

<div class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/information.gif" width="16"
height="16" align="absmiddle" alt="" border="0"></td><td>Note that Cayenne
1.2 supports JDK 1.5 enumerations natively. This example (that infuenced main implementation)
applies to JDK 1.4 and/or Cayenne 1.1.</td></tr></table></div>

<p>An implementation of enumerations as ExtendedTypes in Cayenne. Includes support for
integer and string based enumerations, which allow you to use strongly typed Java variables
backed by constant values to be saved in the database.</p>

<p>Example code can be downloaded from the attachments at the bottom of this page. 
The <span class="error">&#91;enumerations-source.tar.gz|Enumerations Example^enumerations-source.tar.gz&#93;</span>
package contains the required Cayenne source code.  The <span class="error">&#91;enumerations-examples-source.tar.gz|Enumerations
Example^enumerations-examples-source.tar.gz&#93;</span> package contains examples
of two enumerations (integer and string).  Lastly, <span class="error">&#91;enumerations-tapestry-source.tar.gz|Enumerations
Example^enumerations-tapestry-source.tar.gz&#93;</span> contains an implementation
of an IPropertySelectionModel for use in a Tapestry-based application, to enable automatic
mapping of Cayenne enumerations to the user-interface pulldowns.</p>

<h3><a name="EnumerationsExample-DatabaseSetup"></a>Database Setup</h3>

<p>For these examples, the following schema is being used.  It contains an integer column
(<tt>favoriteColor</tt>) and a string column (<tt>favoriteState</tt>)
which will get mapped into Cayenne objects as custom enumerations.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>Example/Test Schema</b></div><div
class="codeContent panelContent">
<pre class="code-sql">mysql&gt; describe UserID;
+---------------+-------------+------+-----+---------+-------+
| Field         | Type        | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| favoriteColor | int(11)     | YES  |     | NULL    |       |
| primaryKey    | int(11)     |      | PRI | 0       |       |
| username      | varchar(16) |      |     |         |       |
| favoriteState | char(2)     | YES  |     | NULL    |       |
+---------------+-------------+------+-----+---------+-------+
4 rows in set (0.09 sec)
</pre>
</div></div>

<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>Example/Test Data</b></div><div
class="codeContent panelContent">
<pre class="code-sql">mysql&gt; <span class="code-keyword">select</span>
* <span class="code-keyword">from</span> UserID;
+---------------+------------+----------+---------------+
| favoriteColor | primaryKey | username | favoriteState |
+---------------+------------+----------+---------------+
|             2 |        260 | mrg      | TN            |
|             3 |        240 | mgentry  | VA            |
|          NULL |        220 | admin    | NULL          |
+---------------+------------+----------+---------------+
3 rows in set (0.06 sec)
</pre>
</div></div>

<h3><a name="EnumerationsExample-CayenneModeler"></a>Cayenne Modeler</h3>

<p>The important thing to note with the modeler definition is <tt>type</tt>
specifies the full path to the enumeration.  For example, even though <tt>favoriteColor</tt>
maps to an integer in the database, the full class name of the custom enumeration is specified
Cayenne Modeler.  This will also cause all of the set/get methods in the generated base class
to be strongly typed to the custom enumeration.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>Modeler Definition</b></div><div
class="codeContent panelContent">
<pre class="code-xml"><span class="code-tag">&lt;obj-entity name=<span
class="code-quote">"UserID"</span> className=<span class="code-quote">"ct2.UserID"</span>
lock-type=<span class="code-quote">"optimistic"</span> dbEntityName=<span class="code-quote">"UserID"</span>&gt;</span>
  &lt;obj-attribute name=<span class="code-quote">"favoriteColor"</span> type=<span
class="code-quote">"ct2.ColorEnumeration"</span>
                 lock=<span class="code-quote">"true"</span> db-attribute-path=<span
class="code-quote">"favoriteColor"</span>/&gt;
  &lt;obj-attribute name=<span class="code-quote">"favoriteState"</span> type=<span
class="code-quote">"ct2.StateEnumeration"</span>
                 lock=<span class="code-quote">"true"</span> db-attribute-path=<span
class="code-quote">"favoriteState"</span>/&gt;
  &lt;obj-attribute name=<span class="code-quote">"username"</span> type=<span
class="code-quote">"java.lang.String"</span>
                 lock=<span class="code-quote">"true"</span> db-attribute-path=<span
class="code-quote">"username"</span>/&gt;
<span class="code-tag">&lt;/obj-entity&gt;</span>
</pre>
</div></div>

<h3><a name="EnumerationsExample-ColorEnumeration"></a>Color Enumeration</h3>

<p>The following code is the example ColorEnumeration, which is an integer-based enumeration.
 StateEnumeration is very similar, but string-based.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>ColorEnumeration.java</b></div><div
class="codeContent panelContent">
<pre class="code-java"><span class="code-keyword">package</span> ct2;

<span class="code-keyword">import</span> org.objectstyle.cayenne.access.types.IntegerEnumeration;

<span class="code-keyword">public</span> class ColorEnumeration <span class="code-keyword">extends</span>
IntegerEnumeration
{
  <span class="code-keyword">public</span> <span class="code-keyword">static</span>
<span class="code-keyword">final</span> ColorEnumeration RED   = <span class="code-keyword">new</span>
ColorEnumeration(<span class="code-quote">"RED"</span>,   <span class="code-keyword">new</span>
<span class="code-object">Integer</span>(1));
  <span class="code-keyword">public</span> <span class="code-keyword">static</span>
<span class="code-keyword">final</span> ColorEnumeration GREEN = <span class="code-keyword">new</span>
ColorEnumeration(<span class="code-quote">"GREEN"</span>, <span class="code-keyword">new</span>
<span class="code-object">Integer</span>(2));
  <span class="code-keyword">public</span> <span class="code-keyword">static</span>
<span class="code-keyword">final</span> ColorEnumeration BLUE  = <span class="code-keyword">new</span>
ColorEnumeration(<span class="code-quote">"BLUE"</span>,  <span class="code-keyword">new</span>
<span class="code-object">Integer</span>(3));

  <span class="code-keyword">private</span> <span class="code-keyword">static</span>
ColorEnumeration enumerations[] = {RED, GREEN, BLUE};

  <span class="code-keyword">private</span> ColorEnumeration(<span class="code-object">String</span>
symbolicName, <span class="code-object">Integer</span> databaseValue)
  {
    <span class="code-keyword">super</span>(symbolicName, databaseValue);
  }

  <span class="code-keyword">public</span> <span class="code-keyword">static</span>
<span class="code-object">int</span> numberOfEnumerations()
  {
    <span class="code-keyword">return</span> numberOfEnumerationsForClass(ColorEnumeration.class);
  }

  <span class="code-keyword">static</span>
  {
    registerEnumerationsForClass(enumerations, ColorEnumeration.class);
  }
}
</pre>
</div></div>

<p>This enumeration creates three constants: <tt>RED</tt>, <tt>GREEN</tt>,
and <tt>BLUE</tt>, which can be used by name in your code with the compiler checking
the types.  These constants have symbolic names (which can be seen when logging SQL) of "RED",
"GREEN", and "BLUE" (the names will usually be the same as the constant, but this is not required)
and database values of 1, 2, and 3, respectively.</p>

<p>The <tt>numberOfEnumerations</tt> method is not required, but is an example
of a helper method you can create to simplify access to the functions provided by the superclass.
 There are many functions provided in the superclass which might be good candidates for helper
methods.</p>

<p>Lastly, the enumerations must be registered in the superclass.  <b>NOTE:</b>
Be very careful if copying/pasting from one enumeration class to another to update all of
the <tt>.class</tt> parts to have the correct class name, otherwise the registration/etc
will silently fail and cause strange behaviors.</p>

<h3><a name="EnumerationsExample-Descriptions"></a>Descriptions</h3>

<p>To support locales, the descriptions for the enumerations are kept in a separate
Java property file, which is loaded using the ResourceLoader and Locale classes.  Refer to
the documentation for those classes for the naming schemes used, etc.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>ColorEnumeration.properties</b></div><div
class="codeContent panelContent">
<pre class="code-java">RED   = Red
GREEN = Green
BLUE  = Blue
</pre>
</div></div>

<p>You can create language-specific versions of this file as needed and specify which
locale in which you want the description looked up.  The left-hand side is the symbolic name
(described above) and the right-hand side is the text to display for the enumeration when
you ask it for it's description.</p>

<h3><a name="EnumerationsExample-Initialization"></a>Initialization</h3>

<p>It is <b>VERY</b> important to initialize your enumerations before you
use them, but only do this once.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>Configure</b></div><div class="codeContent
panelContent">
<pre class="code-java"><span class="code-comment">// Find DataNode
</span>DataDomain domain = Configuration.getSharedConfiguration().getDomain();
DataNode node = domain.getNode(<span class="code-quote">"UntitledDomainNode"</span>);
<span class="code-comment">// Change node name as appropriate
</span>
<span class="code-comment">// Install ExtendedType (must be done before any enumerations
are used)
</span>AbstractEnumeration.registerEnumerationsInDataNode(ColorEnumeration.class, node);
AbstractEnumeration.registerEnumerationsInDataNode(StateEnumeration.class, node);
</pre>
</div></div>

<h3><a name="EnumerationsExample-Inserts%2CUpdates%2CandSelects"></a>Inserts,
Updates, and Selects</h3>

<p>After you have created your enumeration classes, specified them in Cayenne Modeler,
and registered them in your DataNode, they can be used as normal objects in Cayenne.  The
enumeration superclass code handles the translation to the database and back automatically.</p>

<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>Insert (and Update)</b></div><div
class="codeContent panelContent">
<pre class="code-java">DataContext dataContext = DataContext.createDataContext();

UserID userID = (UserID) dataContext.createAndRegisterNewObject(UserID.class);

userID.setFavoriteColor(ColorEnumeration.GREEN);
userID.setFavoriteState(StateEnumeration.TN);
userID.setUsername(<span class="code-quote">"mrg"</span>);

dataContext.commitChanges();
</pre>
</div></div>

<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>Select</b></div><div class="codeContent
panelContent">
<pre class="code-java">Expression expression = Expression.fromString(<span class="code-quote">"favoriteColor
= $color"</span>);
Map map = <span class="code-keyword">new</span> HashMap(1);
map.put(<span class="code-quote">"color"</span>, ColorEnumeration.GREEN);
query = <span class="code-keyword">new</span> SelectQuery(UserID.class, expression.expWithParameters(map));
list = dataContext.performQuery(query);
</pre>
</div></div>
     </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message