| Title: Modeling Enumerations |
| |
| <H2><A name="ModelingEnumerations-MappingandModelingJavaEnumerations"></A>Mapping and Modeling Java Enumerations</H2> |
| |
| <P>Cayenne allows to use any <A href="http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html" class="external-link" rel="nofollow">Java enumeration</A> as an ObjAttribute type. In CayenneModeler's ObjEntity editor, under the Attributes tab, enter the full class name for your enumeration under the Java Type column, and this is it:</P> |
| |
| <P><SPAN class="image-wrap" style=""><IMG src="modeling-enumerations.data/ColorEnum.png" style="border: 0px solid black"></SPAN></P> |
| |
| <P>To convert a DB column value to an enumeration instance and back Cayenne uses enumeration's <TT>name</TT> for character colums (CHAR, VARCHAR, etc) or its <TT>ordinal</TT> for numeric columns. Also Cayenne allows users to explicitly control what value in DB corresponds to a given enumeration instance. To do that, a custom enumeration must implement <TT>org.apache.cayenne.ExtendedEnumeration</TT> interface, overriding <TT>"getDatabaseValue()"</TT> method to provide the DB value. Here is an example of a custom enumeration that maps to DB integers:</P> |
| |
| <DIV class="code panel" style="border-width: 1px;"><DIV class="codeContent panelContent"> |
| <PRE class="code-java"><SPAN class="code-keyword">import</SPAN> org.apache.cayenne.ExtendedEnumeration; |
| |
| <SPAN class="code-keyword">public</SPAN> <SPAN class="code-keyword">enum</SPAN> Color <SPAN class="code-keyword">implements</SPAN> ExtendedEnumeration { |
| RED(3), GREEN(6), BLUE(9); |
| |
| <SPAN class="code-keyword">private</SPAN> <SPAN class="code-object">Integer</SPAN> value; |
| |
| <SPAN class="code-keyword">private</SPAN> Color(<SPAN class="code-object">Integer</SPAN> value) { |
| <SPAN class="code-keyword">this</SPAN>.value = value; |
| } |
| |
| <SPAN class="code-keyword">public</SPAN> <SPAN class="code-object">Integer</SPAN> getDatabaseValue() { |
| <SPAN class="code-keyword">return</SPAN> value; |
| } |
| }</PRE> |
| </DIV></DIV> |
| |
| <P>This instructs Cayenne to read/write 3, 6, and 9 as RED, GREEN, and BLUE, respectively. The order is unimportant - if someone re-orders them to be BLUE, GREEN, and RED in the enum class, all values will still map correctly.</P> |
| |