Friday, January 6, 2012

Enumerated Properties


Enumerated item properties are string properties constrained to a predefined list of valid values and stored as integer codes in the database. A TaggedPropertyEditor is registered for enumerated properties so components like user interfaces can access the list of valid values. For these reasons, the list of valid values should be small. For example, it is not appropriate to use an enumerated attribute for something that might take on more than a hundred values. Instead, you might make a reference to another item with a single int property.

Here is an example of an item descriptor definition that creates an enumerated property named transactionType:

<!-- The "transaction" item type -->
<item-descriptor name="transaction">
  <table name="transaction" id-column-names="xact_id">
    <property name="amount" data-type="int"/>
    <property name="transactionType" data-type="enumerated">
      <option value="credit"/>
      <option value="debit"/>
      <option value="purchase"/>
    </property>
  </table>
</item-descriptor>

In this example the list of valid String values is specified explicitly and the corresponding integer codes are generated by the SQL repository when the template is initialized. It is also possible to specify the integer codes explicitly with the code attribute in the <option> tag:

<property name="transactionType" data-type="enumerated">
  <option value="credit" code="0"/>
  <option value="debit" code="1"/>
  <option value="purchase" code="2"/>
</property>

By default, an enumerated property returns its value as an integer code. You can instead configure an enumerated property so the repository converts the integer code into a string value. Do this with the useCodeForValue attribute in the property definition, as in the following example:

<property name="gender" data-type="enumerated">
  <attribute name="useCodeForValue" value="false"/>
  <option value="male" code="0"/>
  <option value="female" code="1"/>
</property>

In this example, the property sets its useCodeForValue attribute to false. If you get the gender property, the string male or female is returned. Conversely, if useCodeForValue is set to true, the integer code 0 or 1 is returned. If an enumerated property returns an integer code, you can get the property editor for your enumerated property and use that to create a property editor that can convert between the string value and the integer code value. See the JavaBeans specification for a description of PropertyEditors.

No comments:

Popular Posts