Changeset 5673


Ignore:
Timestamp:
Jun 27, 2011, 2:06:13 PM (10 years ago)
Author:
Nicklas Nordborg
Message:

References #1590: Documentation cleanup

Fixed "Core developer reference: Coding rules and guidelines". First 4 sub-sections.

Location:
trunk
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/doc/historical/development/coding/generic.html

    r5014 r5673  
    2727  <link rel=stylesheet type="text/css" href="../../styles.css">
    2828  </head>
    29 <body>
     29<body class="old">
    3030
    3131<div class="navigation">
     
    3838
    3939  <h1>General coding guidelines</h1>
     40  <div class="warning">
     41    NOTE! This document is outdated and has been replaced with newer
     42    documentation. See <a href="../../../html/developerdoc/core_ref/core_ref.rules.style.html">General coding style guidelines</a>
     43  </div>
    4044
    4145  <div class="abstract">
  • trunk/doc/historical/development/coding/process.html

    r4889 r5673  
    44
    55  Copyright (C) 2005 Nicklas Nordborg
    6   Copyright (C) 2006 Jari Häkkinen
     6  Copyright (C) 2006 Jari Hkkinen
    77
    88  This file is part of BASE - BioArray Software Environment.
     
    4040  <div class="warning">
    4141    NOTE! This document is outdated and has been replaced with newer
    42     documentation. See <a href="../../html/developerdoc/core_ref/core_ref.rules.devprocess.html">Development process and other important procedures</a>
     42    documentation. See <a href="../../../html/developerdoc/core_ref/core_ref.rules.devprocess.html">Development process and other important procedures</a>
    4343  </div>
    4444
  • trunk/doc/src/docbook/developerdoc/core_ref.xml

    r5656 r5673  
    223223    <sect2 id="core_ref.rules.style">
    224224      <title>General coding style guidelines</title>
    225       <para>
    226         This documentation is only available in the old format.
    227         See <ulink url="http://base.thep.lu.se/chrome/site/doc/historical/development/coding/generic.html"
    228           >http://base.thep.lu.se/chrome/site/doc/historical/development/coding/generic.html</ulink>
    229       </para>
     225     
     226      <sect3 id="core_ref.rules.naming">
     227        <title>Naming</title>
     228       
     229        <variablelist>
     230        <varlistentry>
     231          <term>General</term>
     232          <listitem>
     233            <para>
     234              All names should be in English. Names should be descriptive and derived from the the
     235              domain the code is intended for. Try to avoid names longer than twenty characters.
     236            </para>
     237          </listitem>
     238        </varlistentry>
     239       
     240        <varlistentry>
     241          <term>Packages</term>
     242          <listitem>
     243            <para>
     244              Package names must be in all lower case letters. The top-level package of
     245              BASE is <code>net.sf.basedb</code>.
     246            </para>
     247          </listitem>
     248        </varlistentry>
     249       
     250        <varlistentry>
     251          <term>Classes and Interfaces</term>
     252          <listitem>
     253            <para>
     254            Names of classes and interfaces should be a concatenation of one or more words.
     255            The initial letter of all words in the name, including the first word, should be upper case
     256            letters. The rest of the characters should be lower case. Example:
     257            </para>
     258            <programlisting language="java">
     259public class SoftwareType
     260{
     261   ...
     262}
     263</programlisting>
     264           
     265          </listitem>
     266        </varlistentry>
     267       
     268        <varlistentry>
     269          <term>Constant member variables</term>
     270          <listitem>
     271            <para>
     272            Constant member variables, usually defined <emphasis>static final</emphasis>, should be named
     273            using all upper case characters. Words in the name should be separated by underscore characters.
     274            Example:
     275            </para>
     276            <programlisting language="java">
     277public static final int VERSION_NUMBER = 3;
     278</programlisting>
     279          </listitem>
     280        </varlistentry>
     281       
     282        <varlistentry>
     283          <term>Private member variables</term>
     284          <listitem>
     285            <para>
     286            Private member variables should be a concatenation of one or more descriptive words.
     287            The initial letter of all words in the name, except the first word, should be upper
     288            case letters. The rest of the characters should be lower case. Example:
     289            </para>
     290            <programlisting language="java">
     291private String loginComment;
     292</programlisting>
     293          </listitem>
     294        </varlistentry>
     295       
     296        <varlistentry>
     297          <term>Methods</term>
     298          <listitem>
     299            <para>
     300            Methods should be named using a descriptive statement, usually made up by several words.
     301            Typically the first word is a verb, stating the action and the others stating the target
     302            and attributes. Lower and upper case letters should then be mixed, with all words in the
     303            name except the first one starting with an upper case letter and the rest being in
     304            lower case letters. Example:
     305            </para>
     306            <programlisting language="java">
     307<![CDATA[
     308public ItemQuery<Annotation> getAllInheritedAnnotations()
     309{
     310   ...
     311}
     312]]>
     313</programlisting>
     314          </listitem>
     315        </varlistentry>
     316       
     317        <varlistentry>
     318          <term>Mutator (get/set) methods</term>
     319          <listitem>
     320            <para>
     321            Avoid direct access to attributes (member variables) from outside of a class.
     322            Instead make attributes private and use mutator methods to access them. Prefix
     323            the mutator methods with get and set respectively to fetch or change an attribute.
     324            If the getter returns a boolean value prefix the mutator method with (typically)
     325            is, has or can. Examples:
     326            </para>
     327            <programlisting language="java">
     328private String name;
     329public String getName()
     330{
     331   return name;
     332}
     333public void setName(String name)
     334{
     335  this.name = name;
     336}
     337
     338private boolean activated;
     339public boolean isActivated()
     340{
     341   return activated;
     342}
     343</programlisting>
     344           
     345          </listitem>
     346        </varlistentry>
     347
     348        <varlistentry>
     349          <term>Exceptions</term>
     350          <listitem>
     351            <para>
     352            The names of Exceptions must end with the word <emphasis>Exception</emphasis>.
     353            Example:
     354            </para>
     355            <programlisting language="java">
     356public class NoMoreNumbersException
     357   extends Exception
     358{
     359   ...
     360}
     361</programlisting>
     362          </listitem>
     363        </varlistentry>
     364      </variablelist>
     365     
     366    </sect3>
     367   
     368    <sect3 id="core_ref.rules.layout">
     369      <title>Layout and comments</title>
     370   
     371      <variablelist>
     372        <varlistentry>
     373          <term>Interface layout</term>
     374          <listitem>
     375            <para>
     376            Interfaces should only have public members, i.e. static attributes and method prototypes.
     377            </para>
     378          </listitem>
     379        </varlistentry>
     380       
     381        <varlistentry>
     382          <term>White space</term>
     383          <listitem>
     384            <para>
     385            All code must be properly indented. In general each new block starts a
     386            new indentation level. Use <emphasis>tab</emphasis> when indenting.
     387            </para>
     388          </listitem>
     389        </varlistentry>
     390       
     391        <varlistentry>
     392          <term>Code blocks</term>
     393          <listitem>
     394            <para>
     395            The starting brace "{" of a code block should be placed on a line by itself at
     396            the same indentation level as the preceeding line of code. The first line in
     397            the new block should be indented one tab-stop more. The ending brace "}"
     398            should be placed at the same indentation level as the matching starting brace.
     399            Use braces even if the code block is only one line. Example:
     400            </para>
     401            <programlisting language="java">
     402public String getName()
     403{
     404   if (name == null)
     405   {
     406      return "unknown";
     407   }
     408   else
     409   {
     410      return name;
     411   }
     412}
     413</programlisting>
     414          </listitem>
     415        </varlistentry>
     416       
     417        <varlistentry>
     418          <term>Javadoc</term>
     419          <listitem>
     420            <para>
     421            Packages, classes, public methods and public attributes should be commented in Javadoc style.
     422            It is recommended that private and protected methods also has some comments, but maybe not
     423            as detailed as the public ones.
     424            </para>
     425           
     426            <itemizedlist>
     427              <listitem>All comments should be in English.</listitem>
     428              <listitem>Do not start each line of a comment with a star.</listitem>
     429            </itemizedlist>
     430           
     431            <para>
     432              More info about Javadoc can be found at: <ulink
     433                url="http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html"
     434                >http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html</ulink>
     435            </para>
     436          </listitem>
     437        </varlistentry>
     438       
     439        <varlistentry>
     440          <term>Package comments</term>
     441          <listitem>
     442            <para>
     443            Place package comments in a file named <filename>package.html</filename> in the
     444            source code directory.
     445            </para>
     446          </listitem>
     447        </varlistentry>
     448       
     449        <varlistentry>
     450          <term>Class comments</term>
     451          <listitem>
     452            <para>
     453            A class comment should start with a general description of the class and what it does.
     454            Use the <code>@author</code> tag to specify the names of the programmers that was involved
     455            in coding the file and the <code>@since</code> tag to specify the version of BASE when the
     456            class first appeared. Example:
     457            </para>
     458            <programlisting language="java">
     459/**
     460   ...
     461   @author Nicklas, Martin
     462   @since 2.0
     463*/
     464public class BasicItem
     465{
     466  ...
     467}
     468</programlisting>
     469          </listitem>
     470        </varlistentry>
     471       
     472        <varlistentry>
     473          <term>Method comments</term>
     474          <listitem>
     475            <para>
     476            A method comment should start with a general description of the method and what it does.
     477            Use <code>@param</code> to describe each parameter and <code>@return</code> to describe
     478            what the method returns. Use <code>@throws</code> to describe all checked exceptions
     479            including when and why they can be thrown. Use <code>@see</code> to link to other related
     480            method and information.
     481            </para>
     482          </listitem>
     483        </varlistentry>
     484       
     485        <varlistentry>
     486          <term>Attribute comments</term>
     487          <listitem>
     488            <para>
     489            If it is a static final attribute, describe what the attribute is for and where it is typically used.
     490            </para>
     491          </listitem>
     492        </varlistentry>
     493       
     494        <varlistentry>
     495          <term>@base.developer</term>
     496          <listitem>
     497            <para>
     498            The <code>@base.developer</code> tag can be used anywhere to add comments that are
     499            mainly targeted to the developers of BASE.
     500            </para>
     501          </listitem>
     502        </varlistentry>
     503
     504        <varlistentry>
     505          <term>@base.internal</term>
     506          <listitem>
     507            <para>
     508            The <code>@base.internal</code> tag can be used at package and class-level
     509            documentation to mark that part of the code as an internal API that should
     510            not be used by plug-ins and other client code. See
     511            <xref linkend="api_overview.public_api" />.
     512            </para>
     513          </listitem>
     514        </varlistentry>
     515       
     516        <varlistentry>
     517          <term>Inline comments</term>
     518          <listitem>
     519            <itemizedlist>
     520              <listitem>All comments should be in English.</listitem>
     521              <listitem>
     522                Comment on why instead of what. Your code should be
     523                clear enough to answer questions on what it does. It is more
     524                important to document why it does it.
     525              </listitem>
     526              <listitem>Do not place end line comments at the end of statements.</listitem>
     527              <listitem>
     528                Do not use decorated banner like comments, as these are hard to maintain.
     529                If more extensive commenting is needed - use Javadoc.
     530              </listitem>
     531            </itemizedlist>
     532         
     533          </listitem>
     534        </varlistentry>
     535       
     536        <varlistentry>
     537          <term>Todo comments</term>
     538          <listitem>
     539            <para>
     540            If there are parts of the code that cannot be completed at the time the majority of the code
     541            is written, place a comment starting with TODO (in capital letters), followed with a
     542            description of what needs to be done. Example:
     543            </para>
     544            <programlisting language="java">
     545public static Date copy(Date value)
     546{
     547   return value == null ? null : new Date(value.getTime());
     548   // TODO: check if there is a better way to copy
     549}
     550</programlisting>
     551          </listitem>
     552        </varlistentry>
     553       
     554        <varlistentry>
     555          <term>Subversion comment and GNU licence message</term>
     556          <listitem>
     557            <para>
     558            Each file should start with a subversion comment and the GNU licence and copyright message.
     559            Non-java files should also include this information, in a format appropriate for the
     560            specific file.
     561            </para>
     562            <programlisting language="java">
     563<![CDATA[
     564/*
     565   $Id$
     566
     567   Copyright (C) Authors contributing to this file.
     568
     569   This file is part of BASE - BioArray Software Environment.
     570   Available at http://base.thep.lu.se/
     571
     572   BASE is free software; you can redistribute it and/or
     573   modify it under the terms of the GNU General Public License
     574   as published by the Free Software Foundation; either version 3
     575   of the License, or (at your option) any later version.
     576
     577   BASE is distributed in the hope that it will be useful,
     578   but WITHOUT ANY WARRANTY; without even the implied warranty of
     579   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     580   GNU General Public License for more details.
     581
     582   You should have received a copy of the GNU General Public License
     583   along with BASE. If not, see <http://www.gnu.org/licenses/>.
     584*/
     585]]>
     586</programlisting>
     587          </listitem>
     588        </varlistentry>
     589        </variablelist>
     590       
     591      </sect3>
     592
     593    <sect3 id="core_ref.rules.statements">
     594      <title>Statements</title>
     595
     596        <variablelist>       
     597        <varlistentry>
     598          <term>Package and import statements</term>
     599          <listitem>
     600            <para>
     601            The package statement is the first statement to appear in the source file. All declared classes
     602            must belong to a named package. It is not allowed for classes to belong to the "default" package,
     603            i.e. to omit the package statement in the source file. Exception: Test code may belong to the
     604            default package.
     605            </para>
     606           
     607            <para>
     608            Import statements should follow directly after the package statement. Try to avoid
     609            preceeding class names in code with package names. Instead use import statements.
     610            </para>
     611           
     612            <para>
     613            Wildcards in import statements make it difficult to see dependencies,
     614            other than those to packages. Therefore import classes/interfaces explicitely.
     615            The only exception is when classes in subpackages to the current package are accessed.
     616            Such items are either imported explicitely or the whole subpackage may be imported with
     617            wildcard. However, avoid wildcard imports when subpackages are large - more than approximately
     618            4 items.
     619            </para>
     620           
     621            <para>
     622            Do not explicitely import packages or classes not used in your program code.
     623            Try to maintain an alphabetical order among the imported classes. Group
     624            classes from the same package. Most IDE:s have functionality for maintaining
     625            import statements. Use it.
     626            </para>
     627           
     628          </listitem>
     629        </varlistentry>
     630       
     631        <varlistentry>
     632          <term>Inside a class, attributes and methods should be organised in the following order:</term>
     633          <listitem>
     634            <itemizedlist>
     635              <listitem>public static final attributes</listitem>
     636              <listitem>other static attributes</listitem>
     637              <listitem>public static methods</listitem>
     638              <listitem>other static methods</listitem>
     639              <listitem>private attributes</listitem>
     640              <listitem>constructors</listitem>
     641              <listitem>Methods defined by interfaces, grouped by the interface in which they are defined</listitem>
     642              <listitem>Methods that override a method from a superclass, with methods from the topmost superclass first</listitem>
     643              <listitem>Additional methods for the specific class</listitem>
     644            </itemizedlist>
     645          </listitem>
     646        </varlistentry>
     647       
     648        <varlistentry>
     649          <term>Classes and interfaces</term>
     650          <listitem>
     651            <para>
     652            Class and interface statements should be organized in the following manner:
     653            </para>
     654           
     655            <itemizedlist>
     656              <listitem>class or interface statement</listitem>
     657              <listitem>extends statement indented on a separate row</listitem>
     658              <listitem>implements statement indented on one or more rows</listitem>
     659              <listitem>class body</listitem>
     660            </itemizedlist>
     661            <programlisting language="java">
     662public class SomeClass
     663   extends SomeBase
     664   implements Clonable, SomeInterface
     665{
     666   ...
     667}
     668
     669public interface Testable
     670   extends Clonable
     671{
     672   ...
     673}
     674</programlisting>
     675
     676          </listitem>
     677        </varlistentry>
     678       
     679        <varlistentry>
     680          <term>Methods</term>
     681          <listitem>
     682            <para>
     683            If a method throws checked exceptions, these should be declared indented on a separate row directly
     684            after the method declaration. Example:
     685            </para>
     686            <programlisting language="java">
     687public int getNextValue(int previousValue)
     688   throws NoMoreValuesException
     689{
     690   ...
     691}
     692</programlisting>
     693          </listitem>
     694        </varlistentry>
     695       
     696        <varlistentry>
     697          <term>Local variables</term>
     698          <listitem>
     699            <para>
     700            Local variables should be declared and initialized where they are used.
     701            They should be declared in the smallest possible scope. Avoid overloading
     702            variable names in inner blocks.
     703            </para>
     704          </listitem>
     705        </varlistentry>
     706       
     707        <varlistentry>
     708          <term>Array declarations</term>
     709          <listitem>
     710            <para>
     711            The square brackets indicating an array of something should be immediately to
     712            the right of whatever class or datatype the array consists of
     713            (e.g. <code>String[] args</code>) do not use C-style array declarations
     714            (<code>String args[]</code>).
     715            </para>
     716          </listitem>
     717        </varlistentry>
     718       
     719        <varlistentry>
     720          <term>Conditional statements</term>
     721          <listitem>
     722            <itemizedlist>
     723              <listitem>
     724              There must always be braces around the block following the condition control structure, even if it's
     725              just a single statement block. This doesn't apply to the cases when the single statement is on
     726              the same line as the condition.
     727              </listitem>
     728              <listitem>Avoid placing statements resulting in side effects (e.g. function calls) in the condition construct.</listitem>
     729              <listitem>Do not jump out of conditional blocks with break, return or exit. The exception is the usage of break in switch-statements.</listitem>
     730              <listitem>Use continue-statements in for- and while- loops with caution. It's recommended to mark the statement with a clear comment.</listitem>
     731            </itemizedlist>
     732           
     733            <programlisting language="java">
     734// IF-statements:
     735if (...)
     736{
     737   ...
     738}
     739else
     740{
     741   ...
     742}
     743
     744if (...) ...;
     745
     746
     747// FOR-statements:
     748for (init; condition; update)
     749{
     750   ...
     751   /* #### CONTINUE-STATEMENT #### */
     752   if (...) continue;
     753   ...
     754}
     755
     756// WHILE-statement:
     757while (condition)
     758{
     759   ...
     760}
     761
     762// DO-WHILE-statement:
     763do
     764{
     765   ...
     766}
     767while (condition);
     768
     769// SWITCH-statement:
     770switch (operand)
     771{
     772   case: ...
     773   {
     774      ...
     775      break;
     776   }
     777   default:
     778   {
     779      ...
     780   }
     781}
     782
     783
     784// Exception blocks:
     785try
     786{
     787   ...
     788}
     789catch (SpecialException se)
     790{
     791   ...
     792}
     793catch (Exception e)
     794{
     795   ...
     796}
     797finally
     798{
     799   ...
     800}
     801</programlisting>
     802          </listitem>
     803        </varlistentry>     
     804        </variablelist>       
     805      </sect3>
     806
    230807    </sect2>
    231808 
     
    237814        and plug-ins should continue to run in the next release of BASE,
    238815        without the need to change them. It may sound easy but there are
    239         many things to watch out for.
     816        many things to watch out for. There is a great article about this subject on <ulink
     817        url="http://wiki.eclipse.org/index.php/Evolving_Java-based_APIs"
     818          >http://wiki.eclipse.org/index.php/Evolving_Java-based_APIs</ulink>.
    240819      </para>
     820     
     821     
     822      <variablelist>
     823        <varlistentry>
     824          <term>The Public API</term>
     825          <listitem>
     826            <para>
     827            Not all code in BASE is considered to be part of the public
     828            API. See <xref linkend="api_overview.public_api" /> and
     829            <ulink url="../../../api/index.html">the javadoc</ulink>
     830            for information about the public API. Changes made to
     831            the internal API does not have to follow the same rules.
     832            </para>
     833          </listitem>
     834        </varlistentry>
     835       
     836        <varlistentry>
     837          <term>Binary compatibility</term>
     838          <listitem>
     839            <para>
     840            This is hardest requirement and means that existing binaries must run
     841            with the updated BASE version. The Eclipse document discusses this
     842            type of compatibility in great detail.
     843            </para>
     844          </listitem>
     845        </varlistentry>
     846
     847        <varlistentry>
     848          <term>Contract compatibility</term>
     849          <listitem>
     850            <para>
     851            Methods should continue to do things in the same ways as before. Avoid
     852            introducing side-effects and expanding/contracting the allowed range
     853            of return or parameter values. This may not always be easy to keep this
     854            type of compatibility. For example, adding a new option to an enumeration
     855            may break code that is not prepared for it.
     856            </para>
     857          </listitem>
     858        </varlistentry>
     859
     860        <varlistentry>
     861          <term>Internal data structure compatibility</term>
     862          <listitem>
     863            <para>
     864            It may not be possible to keep the internal data structures. If they change the
     865            update script should convert the old data to the new format. Avoid exposing
     866            the internal data structure to client applications. Use wrapper classes, etc,
     867            to hide as much as possible.
     868            </para>
     869          </listitem>
     870        </varlistentry>
     871
     872        <varlistentry>
     873          <term>Source code compatibility</term>
     874          <listitem>
     875            <para>
     876            This is not an important issue and in most cases the problems are easy to fix.
     877            </para>
     878          </listitem>
     879        </varlistentry>
     880     
     881      </variablelist>
    241882     
    242883      <important>
     
    247888        </para>
    248889      </important>
    249      
    250       <para>
    251         There is a great article about this subject on <ulink
    252         url="http://wiki.eclipse.org/index.php/Evolving_Java-based_APIs"
    253           >http://wiki.eclipse.org/index.php/Evolving_Java-based_APIs</ulink>.
    254         This is what we will try to comply with.
    255       </para>
    256      
    257       <sect3 id="core_ref.rules.compatibility.public_api">
    258         <title>Does the changes affect the Public API?</title>
    259        
    260         <para>
    261           See <xref linkend="api_overview.public_api" /> and
    262           <ulink url="http://base.thep.lu.se/chrome/site/doc/api/index.html"
    263           >the javadoc</ulink>for information
    264           about the public API.
    265         </para>
    266        
    267         <para>
    268           Changes made to the non-public API does not have to follow the
    269           same rules.
    270         </para>
    271       </sect3>
    272      
    273       <sect3 id="core_ref.rules.compatibility.contract">
    274         <title>Contract compatibility</title>
    275        
    276         <para>
    277           TODO
    278         </para>
    279        
    280       </sect3>
    281      
    282       <sect3 id="core_ref.rules.compatibility.binary">
    283         <title>Binary compatibility</title>
    284        
    285         <para>
    286           TODO
    287         </para>
    288        
    289       </sect3>
    290      
    291       <sect3 id="core_ref.rules.compatibility.data">
    292         <title>Internal data structure compatibility</title>
    293        
    294         <para>
    295           TODO
    296         </para>
    297        
    298       </sect3>
    299      
    300       <sect3 id="core_ref.rules.compatibility.source">
    301         <title>Source code compatibility</title>
    302        
    303         <para>
    304           TODO
    305         </para>
    306        
    307       </sect3>
    308      
     890 
    309891    </sect2>
    310892   
     
    317899      </para>
    318900     
    319       <sect3 id="core_ref.rules.datalayer.methodorder">
    320         <title>Attributes and methods order</title>
    321         <para>
    322           Inside a class, attributes and methods should be organised in related groups,
    323           ie. the private attribute is together with the getter and setter methods that uses
    324           that attribute. This makes it easy to re-use existing code with copy-and-paste
    325           operations.
    326         </para>
    327          
    328         <programlisting language="java">
     901      <variablelist>
     902        <varlistentry>
     903          <term>Class and interface names</term>
     904          <listitem>
     905            <para>
     906              Class names should follow the general guidelines, but should in most
     907              cases end with <classname>Data</classname>.
     908            </para>
     909            <programlisting language="java">
     910public class SampleData
     911   extends CommonData
     912   implements DiskConsumableData
     913{
     914   ...
     915}
     916</programlisting>
     917          </listitem>
     918        </varlistentry>
     919
     920        <varlistentry>
     921          <term>Attributes and methods order</term>
     922          <listitem>
     923            <para>
     924              Inside a class, attributes and methods should be organised in related groups,
     925              ie. the private attribute is together with the getter and setter methods that uses
     926              that attribute. This makes it easy to re-use existing code with copy-and-paste
     927              operations.
     928            </para>
     929            <programlisting language="java">
    329930public static int long MAX_ADDRESS_LENGTH = 255;
    330931private String address;
     
    354955}       
    355956</programlisting>
    356         </sect3>
    357        
    358         <sect3 id="core_ref.rules.datalayer.classnames">
    359           <title>Class and interface names</title>
    360         <para>
    361           Class names should follow the general guidelines, but should in most
    362           cases end with <classname>Data</classname>.
    363         </para>
    364         <programlisting language="java">
    365 public class SampleData
    366    extends CommonData
    367    implements DiskConsumableData
    368 {
    369    ...
    370 }
    371 </programlisting>
    372       </sect3>
    373       <sect3 id="core_ref.rules.datalayer.basicclasses">
    374         <title>Extend/implement the basic classes and interfaces</title>
    375         <para>
    376           Each data-class must inherit from one of the already existing abstract base classes.
    377           They contain code that is common to all classes, for example implementations of
    378           the <methodname>equals()</methodname> and <methodname>hashCode()</methodname>
    379           methods or how to link with the owner of an item. For information about
    380           which classes/interfaces that can be used see <xref linkend="data_api.basic" />.
    381         </para>
    382       </sect3>
    383 
    384       <sect3 id="core_ref.rules.datalayer.constructor">
    385         <title>Define a public no-argument constructor</title>
    386         <para>
    387           Always define a public a no-argument constructor. No other constructors are needed.
    388           If we want to use other persistence mechanisms or serializability in the future
    389           this type of constructor is probably the most compatible. The constructor should
    390           be empty and not contain any code. Do not initialise properties or create new objects
    391           for internal use. Most of the time the object is loaded by
    392           Hibernate and Hibernate will ensure that it is properly initialised by calling
    393           all setter methods.
    394         </para>
    395 
    396         <para>
    397           For example, a many-to-many relation usually has a <interfacename>Set</interfacename>
    398           or a <interfacename>Map</interfacename> to hold the links to the other objects. Do not
    399           create a new <classname>HashSet</classname> or <classname>HashMap</classname>
    400           in the constructor. Wait until the get method is called and only create a new
    401           object if Hibernate hasn't already called the setter method with it's own object.
    402           See the code example below. There is also more information about this in
    403           <xref linkend="core_ref.rules.datalayer.manytomany" />.
    404         </para>
    405        
    406         <programlisting language="java">
     957          </listitem>
     958        </varlistentry>
     959
     960        <varlistentry>
     961          <term>Extend/implement the basic classes and interfaces</term>
     962          <listitem>
     963            <para>
     964            Each data-class must inherit from one of the already existing abstract base classes.
     965            They contain code that is common to all classes, for example implementations of
     966            the <methodname>equals()</methodname> and <methodname>hashCode()</methodname>
     967            methods or how to link with the owner of an item. For information about
     968            which classes/interfaces that can be used see <xref linkend="data_api.basic" />.
     969            </para>
     970          </listitem>
     971        </varlistentry>
     972
     973        <varlistentry>
     974          <term>Define a public no-argument constructor</term>
     975          <listitem>
     976            <para>
     977            Always define a public no-argument constructor. No other constructors are needed.
     978            If we want to use other persistence mechanisms or serializability in the future
     979            this type of constructor is probably the most compatible. The constructor should
     980            be empty and not contain any code. Do not initialise properties or create new objects
     981            for internal use. Most of the time the object is loaded by
     982            Hibernate and Hibernate will ensure that it is properly initialised by calling
     983            all setter methods.
     984            </para>
     985            <para>
     986              For example, a many-to-many relation usually has a <interfacename>Set</interfacename>
     987              or a <interfacename>Map</interfacename> to hold the links to the other objects. Do not
     988              create a new <classname>HashSet</classname> or <classname>HashMap</classname>
     989              in the constructor. Wait until the getter method is called and only create a new
     990              object if Hibernate hasn't already called the setter method with it's own object.
     991              See the code example below. There is also more information about this in
     992              <xref linkend="core_ref.rules.datalayer.manytomany" />.
     993            </para>
     994            <programlisting language="java">
     995<![CDATA[
    407996// From GroupData.java
    408997public GroupData()
    409998{}
    410999
    411 private Set&lt;UserData&gt; users;
    412 public Set&lt;UserData&gt; getUsers()
    413 {
    414    if (users == null) users = new HashSet&lt;UserData&gt;();
     1000private Set<UserData> users;
     1001public Set<UserData> getUsers()
     1002{
     1003   if (users == null) users = new HashSet<UserData>();
    4151004   return users;
    4161005}
    417 </programlisting>
    418 
    419         <para>
    420         See also:
    421         </para>
    422        
    423         <itemizedlist>
    424         <listitem>
    425           <para>
    426           "Hibernate in action", chapter 3.2.3 "Writing POJOs", page 67-69
    427           </para>
    428         </listitem>
    429         <listitem>
    430           <para>
    431           Hibernate user documentation: <ulink
    432             url="http://www.hibernate.org/hib_docs/reference/en/html/persistent-classes.html#persistent-classes-pojo-constructor">4.1.1.
    433             Implement a no-argument constructor</ulink>
    434           </para>
    435         </listitem>
    436         </itemizedlist>
    437 
    438       </sect3>
    439 
    440       <sect3 id="core_ref.rules.datalayer.identity">
    441         <title>Object identity</title>
    442         <para>
    443           We use database identity to compare objects, ie. two objects are considered
    444           equal if they are of the same class and have the same id, thus representing the
    445           same database row. All this stuff is implemented by the BasicData class. Therefore
    446           it is required that all classes are subclasses of this class. It is recommended
    447           that the <methodname>equals()</methodname> or <methodname>hashCode()</methodname>
    448           methods are not overridden by any of the subclasses. We would have liked to make
    449           them final, but then the proxy feature of Hibernate would not work.
    450         </para>
    451        
    452         <warning>
    453           <title>Avoid mixing saved and unsaved objects</title>
    454           <para>
    455             The approch used for object identity may give us a problem if we mix objects
    456             which hasn't been saved to the database, with objects loaded from the database.
    457             Our recommendation is to avoid that, and save any objects to the database before
    458             adding them to sets, maps or any other structure that uses the
    459             <methodname>equals()</methodname> and <methodname>hashCode()</methodname> methods.
    460           </para>
    461           <para>
    462             To be more specific, the problem arises because the following two rules for
    463             hascodes are contradicting when the hashcode is based on the database id:
    464           </para>
    465           <orderedlist>
    466           <listitem>
    467             <para>
    468             The hash code of an object mustn't change
    469             </para>
    470           </listitem>
    471           <listitem>
    472             <para>
    473             Equal objects must have equal hash code
    474             </para>
    475           </listitem>
    476           </orderedlist>
    477           <para>
    478             For objects in the database, the hash code is based on the id. For new objects,
    479             which doesn't have an id yet, we fall back to the system hash code. But, what
    480             happens when we save the new object to the database? If nobody has asked for
    481             the hash code it is safe to use the id, otherwise we must stick with the system
    482             hash code. Now, imagine that we load the same object from the database in
    483             another Hibernate session. What will now happen? The loaded object will have
    484             it's hash code based on the id but the original object is still using the
    485             system hash code, which most likely is not the same as the id. Yet, the
    486             <methodname>equals()</methodname> method returns true. This is a violation
    487             of the contract for the equals method. If these two objects are used in a set
    488             it may cause unexpected behaviour. Therefore, do not put new objects in a
    489             set, or other collection, that calls the <methodname>hashCode()</methodname>
    490             method before the object is saved to the database.         
    491           </para>
    492         </warning>
    493        
    494         <para>
    495         See also:
    496         </para>
    497         <itemizedlist>
    498         <listitem>
    499           <para>
    500           "Hibernate in action", chapter 3.4 "Understanding object identity", page 87-90
    501           </para>
    502         </listitem>
    503         <listitem>
    504           <para>
    505           "Hibernate in action", chapter 4.1.4 "The scope of object identity", page 119-121
    506           </para>
    507         </listitem>
    508         <listitem>
    509           <para>
    510           "Hibernate in action", chapter 4.1.6 "Implementing equals() and hashCode(), page 122-126
    511           </para>
    512         </listitem>
    513         <listitem>
    514           <para>
    515           Hibernate user documentation: <ulink
    516             url="http://www.hibernate.org/hib_docs/reference/en/html/persistent-classes.html#persistent-classes-equalshashcode">4.3. Implementing equals() and hashCode()</ulink>
    517           </para>
    518         </listitem>
    519         </itemizedlist>
    520       </sect3>
    521 
    522       <sect3 id="core_ref.rules.datalayer.nofinal">
    523         <title>No final methods</title>
    524         <para>
    525           No methods should be tagged with the <constant>final</constant> keyword. This is a
    526           requirement to be able to use the proxy feature of Hibernate, which we need for
    527           performance reasons.
    528         </para>
    529 
    530         <para>
    531         See also:
    532         </para>
    533         <itemizedlist>
    534         <listitem>
    535           <para>
    536           Hibernate user documentation: <ulink
    537             url="http://www.hibernate.org/hib_docs/reference/en/html/persistent-classes.html#persistent-classes-pojo-final">4.1.3. Prefer non-final classes</ulink>
    538           </para>
    539         </listitem>
    540         <listitem>
    541           <para>
    542           Hibernate user documentation: <ulink
    543             url="http://www.hibernate.org/hib_docs/reference/en/html/performance.html#performance-fetching-proxies">19.1.3. Single-ended association proxies</ulink>
    544           </para>
    545         </listitem>
    546         </itemizedlist>
    547 
    548       </sect3>
    549 
    550       <sect3 id="core_ref.rules.datalayer.cache">
    551         <title>Second-level cache</title>
    552         <para>
    553           To gain performance we use the second-level cache of Hibernate. It is a transparent
    554           feature that doesn't affect the code in any way. The second-level cache is configured
    555           in the <filename>hibernate.cfg.xml</filename> and <filename>ehcache.xml</filename>
    556           files and not in the individual class mapping files. BASE is shipped with a standard
    557           configuration, but different deployment scenarios may have to fine-tune the cache
    558           settings for that particular hardware/software setup. It is beyond the scope of
    559           this document to discuss this issue.
    560         </para>
    561        
    562         <para>
    563           The second-level cache is suitable for objects that are rarely modified but
    564           are often needed. For example, we do not expect the user information represented
    565           by the <classname docapi="net.sf.basedb.core.data">UserData</classname> object to change very often, but it is
    566           displayed all the time as the owner of various items.
    567         </para>
    568        
    569         <para>
    570           It is required that one thinks a bit of the usage of a class before coming
    571           up with a good caching strategy. We have to answer the following questions:
    572         </para>
    573        
    574         <orderedlist>
    575         <listitem>
    576           <para>
    577           Should objects of this class be cached at all?
    578           </para>
    579         </listitem>
    580         <listitem>
    581           <para>
    582           How long timeout should we use?
    583           </para>
    584         </listitem>
    585         <listitem>
    586           <para>
    587           How many objects should we keep in memory or on disk?
    588           </para>
    589         </listitem>
    590         </orderedlist>
    591        
    592         <para>
    593           The first question is the most important. Good candidates are classes with few
    594           objects that change rarely, but are read often. Also, objects which are linked
    595           to by many other objects are good candidates. The <classname docapi="net.sf.basedb.core.data">UserData</classname>
    596           class is an example which matches all three requirements. The <classname docapi="net.sf.basedb.core.data">LabelData</classname>
    597           class is an example which fulfils the first two. The <classname docapi="net.sf.basedb.core.data">BioMaterialEventData</classname>
    598           class is on the other hand a bad cache candidate, since it is not linked to any
    599           other object than a <classname docapi="net.sf.basedb.core.data">BioMaterialData</classname> object.
    600         </para>
    601        
    602         <para>
    603           The answer to the second question depends on how often an object is modified.
    604           For most objects this time is probably several days or months, but we would
    605           not gain much by keeping objects in the cache for so long. Suddenly, the
    606           information has changed and we won't risk that old information is kept that
    607           long. We have set the timeout to 1 hour for all classes so far, and we don't
    608           recommend a longer timeout. The only exception is for immutable objects, that
    609           cannot be changed at all, which may have an infinite timeout.
    610         </para>
    611        
    612         <para>
    613           The answer to the third question depends a lot on the hardware (available memory).
    614           With lots of memory we can afford to cache more objects. Caching to disk is not
    615           really necessary if the database is on the same machine as the web server, but
    616           if it is on another machine we have to consider the network delay to connect
    617           to the database versus the disk access time. The default configuration does not
    618           use disk cache.
    619         </para>
    620 
    621         <para>
    622         See also:
    623         </para>
    624         <itemizedlist>
    625         <listitem>
    626           <para>
    627           "Hibernate in action", chapter 5.3 "Caching theory and practice", page 175-194.
    628           </para>
    629         </listitem>
    630         <listitem>
    631           <para>
    632           Hibernate user documentation: <ulink
    633             url="http://www.hibernate.org/hib_docs/reference/en/html/performance.html#performance-cache">19.2. The Second Level Cache</ulink>
    634           </para>
    635         </listitem>
    636         </itemizedlist>
    637 
    638       </sect3>
    639 
    640       <sect3 id="core_ref.rules.datalayer.proxies">
    641         <title>Proxies</title>
    642        
    643         <para>
    644           Proxies are also used to gain performance, and they may have some impact on
    645           the code. Proxies are created at runtime (by Hibernate) as a subclass of the
    646           actual class but are not populated with data until some method of the object
    647           is called. The data is loaded from the database the first time a method other
    648           than <methodname>getId()</methodname> is called. Thus, we can avoid loading
    649           data that is not needed at a particular time.
    650         </para>
    651        
    652         <para>
    653           There can be a problem with using the <code>instanceof</code> operator with proxies
    654           and the table-per-class-hierarchy mapping. For example, if we have the abstract
    655           class <classname>Animal</classname> and subclasses <classname>Cat</classname>
    656           and <classname>Dog</classname>. The proxy of an <classname>Animal</classname> is a
    657           runtime generated subclass of <classname>Animal</classname>, since we do not know if it
    658           is a <classname>Cat</classname> or <classname>Dog</classname>. So,
    659           <code>x instanceof Dog</code> and <code>x instanceof Cat</code> would both return
    660           false. If we hadn't used a proxy, at least one of them would always be true.
    661         </para>
    662        
    663         <para>
    664           Proxies are only used when a not-null object is linked with many-to-one or
    665           one-to-one from another object. If we ask for a specific object by id, or by a
    666           query, we will never get a proxy. Therefore, it only makes sense to enable
    667           proxies for classes that can be linked from other classes. One-to-one links on
    668           the primary key where null is allowed silently disables the proxy feature,
    669           since Hibernate doesn't know if there is an object or not without querying
    670           the database.
    671         </para>
    672        
    673         <bridgehead>Proxy vs. cache</bridgehead>
    674         <para>
    675           The goal of a proxy and the second-level cache are the same: to avoid hitting the
    676           database. It is perfectly possible to enable both proxies and the cache for a
    677           class. Then we would start with a proxy and as soon as a method is called Hibernate
    678           would look in the second-level cache. Only if it is not there it would be loaded
    679           from the database. But, do we really need a proxy in the first place? Well, I think
    680           it might be better to use only the cache or only proxies. But, this also makes it
    681           even more important that the cache is configured correctly so there is a high
    682           probability that the object is already in the cache.
    683         </para>
    684        
    685         <para>
    686           If a class has been configured to use the second-level cache, we recommend
    687           that proxies are disabled. For child objects in a parent-child relationship proxies
    688           should be disabled, since they have no other links to them than from the parent.
    689           If a class can be linked as many-to-one from several other classes it makes sense
    690           to enable proxies. If we have a long chain of many-to-one relations it may also make
    691           sense to enable proxies at some level, even if the second-level cache is used.
    692           In that case we only need to create one proxy instead of looking up several objects
    693           in the cache. Also, think about how a particular class most commonly will be used
    694           in a client application. For example, it is very common to display the name of the
    695           owner of an item, but we are probably not interested in displaying quota
    696           information for that user. So, it makes sense to put users in the second-level
    697           cache and use proxies for quota information.
    698         </para>
    699        
    700         <warning>
    701           <title>Batchable classes and stateless sessions</title>
    702           <para>
    703             Starting with Hibernate 3.1 there is a new stateless session feature. A
    704             stateless session has no first-level cache and doesn't use the second-level
    705             cache either. This means that if we load an item with a stateless session
    706             Hibernate will always traverse many-to-one and one-to-one associations and
    707             load those objects as well, unless they are configured to use proxies.
    708           </para>
    709          
    710           <para>
    711             Stateless sessions are used by batchable items (reporters, raw data and features)
    712             since they are many and we want to use as little memory as possible. Here it
    713             is required that proxies are enabled for all items that are linked from any of
    714             the batchable items, ie. <classname docapi="net.sf.basedb.core">RawBioAssay</classname>,
    715             <classname docapi="net.sf.basedb.core">ReporterType</classname>,
    716             <classname docapi="net.sf.basedb.core">ArrayDesignBlock</classname>, etc.
    717             If we don't do this Hibernate will generate multiple additional select
    718             statements for the same parent item which will affect performance
    719             in a bad way.
    720           </para>
    721          
    722           <para>
    723             On the other hand, the proxies created from a stateless session cannot later
    724             be initialised. We have to get the ID from the proxy and the load the object
    725             using the regular session. But this can also results in lots of additional select
    726             statements so if it is known before that we need some information it is recommended
    727             that a FETCH JOIN is used so that we get fully initialized objects instead of
    728             proxies to begin with.
    729           </para>
    730         </warning>
    731        
    732         <para>
    733           Here is a table which summarises different settings for the second-level cache,
    734           proxies, batch fetching and many-to-one links. Batch fetching and many-to-one links
    735           are discussed later in this document.
    736         </para>
    737        
    738         <para>
    739           First, decide if the second-level cache should be enabled or not. Then, if
    740           proxies should be enabled or not. The table then gives a reasonable setting for
    741           the batch size and many-to-one mappings. NOTE! The many-to-one mappings are
    742           the links from other classes to this one, not links from this class.
    743         </para>
    744        
    745         <para>
    746           The settings in this table are not absolute rules. In some cases there might
    747           be a good reason for another combination. Please, write a comment about why
    748           the recommendations were not followed.
    749         </para>
    750        
    751         <table id="core_ref.rules.datalayer.cacheproxysettings">
    752           <title>Choosing cache and proxy settings</title>
    753           <tgroup cols="4">
    754             <colspec colname="cache" />
    755             <colspec colname="proxy" />
    756             <colspec colname="batchsize" />
    757             <colspec colname="outerjoin" />
    758            
    759             <thead>
    760               <row>
    761                 <entry>Global configuration</entry>
    762                 <entry namest="proxy" nameend="batchsize">Class mapping</entry>
    763                 <entry>Many-to-one mapping</entry>
    764               </row>
    765               <row>
    766                 <entry>Cache</entry>
    767                 <entry>Proxy</entry>
    768                 <entry>Batch-size</entry>
    769                 <entry>Outer-join</entry>
    770               </row>
    771             </thead>
    772             <tbody>
    773               <row>
    774                 <entry>no</entry>
    775                 <entry>no*</entry>
    776                 <entry>yes</entry>
    777                 <entry>true</entry>
    778               </row>
    779               <row>
    780                 <entry>yes</entry>
    781                 <entry>no*</entry>
    782                 <entry>no</entry>
    783                 <entry>false</entry>
    784               </row>
    785               <row>
    786                 <entry>no</entry>
    787                 <entry>yes</entry>
    788                 <entry>yes</entry>
    789                 <entry>false</entry>
    790               </row>
    791               <row>
    792                 <entry>yes</entry>
    793                 <entry>yes</entry>
    794                 <entry>no</entry>
    795                 <entry>false</entry>
    796               </row>
    797             </tbody>
    798           </tgroup>
    799         </table>
    800        
    801         <para>
    802           * = Do not use this setting for classes which are many-to-one linked from a batchable
    803           class.
    804         </para>
    805        
    806         <para>
    807         See also:
    808         </para>
    809         <itemizedlist>
    810         <listitem>
    811           <para>
    812           "Hibernate in action", chapter 4.4.6 "Selecting a fetching strategy in mappings", page 146-147
    813           </para>
    814         </listitem>
    815         <listitem>
    816           <para>
    817           "Hibernate in action", chapter 6.4.1 "Polymorphic many-to-one associations", page 234-236
    818           </para>
    819         </listitem>
    820         <listitem>
    821           <para>
    822           Hibernate user documentation: <ulink
    823             url="http://www.hibernate.org/hib_docs/reference/en/html/performance.html#performance-fetching-proxies">19.1.3. Single-ended association proxies</ulink>
    824           </para>
    825         </listitem>
    826         </itemizedlist>
    827        
    828       </sect3>
    829      
    830       <sect3 id="core_ref.rules.datalayer.hibernate">
    831         <title>Hibernate mappings</title>
    832        
    833         <para>
    834           We use Javadoc tags to specify the database mapping needed by Hibernate.
    835           The tags are processed by XDoclet at build time which generates the XML-based
    836           Hibernate mapping files.
    837         </para>
    838        
    839         <note>
    840           <title>XDoclet doesn't support all mappings</title>
    841           <para>
    842           The XDoclet that we use was developed to generate mapping files for
    843           Hibernate 2.x. Since then, Hibernate has released several 3.x versions,
    844           and the mapping file structure has changed. Some changes can be handled by
    845           generating a corresponding 2.x mapping and then converting it to a 3.x
    846           mapping at build time using simple search-and-replace operations.
    847           One such case is to update the DTD reference to the 3.0 version instead of
    848           the 2.0 version. Other changes can't use this approach. Instead we have to
    849           provide extra mappings inside an XML files. This is also needed if we need
    850           to use some of the new 3.x features that has no 2.x counterpart.
    851           </para>
    852         </note>
    853        
    854         <simplesect id="core_ref.rules.datalayer.class">
    855           <title>Class mapping</title>
    856          
    857           <programlisting language="java">
     1006]]>
     1007</programlisting>
     1008
     1009            <para>
     1010            See also:
     1011            </para>
     1012           
     1013            <itemizedlist>
     1014            <listitem>
     1015              <para>
     1016              "Hibernate in action", chapter 3.2.3 "Writing POJOs", page 67-69
     1017              </para>
     1018            </listitem>
     1019            <listitem>
     1020              <para>
     1021              Hibernate reference documentation: <ulink
     1022                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/persistent-classes.html#persistent-classes-pojo-constructor">4.1.1.
     1023                Implement a no-argument constructor</ulink>
     1024              </para>
     1025            </listitem>
     1026            </itemizedlist>
     1027
     1028          </listitem>
     1029        </varlistentry>
     1030
     1031        <varlistentry>
     1032          <term>Object identity</term>
     1033          <listitem>
     1034            <para>
     1035              We use database identity to compare objects, ie. two objects are considered
     1036              equal if they are of the same class and have the same id, thus representing the
     1037              same database row. All this stuff is implemented by the <classname
     1038              docapi="net.sf.basedb.core.data">BasicData</classname> class. Therefore
     1039              it is required that all classes are subclasses of this class. It is recommended
     1040              that the <methodname>equals()</methodname> or <methodname>hashCode()</methodname>
     1041              methods are not overridden by any of the subclasses. We would have liked to make
     1042              them final, but then the proxy feature of Hibernate would not work.
     1043            </para>
     1044           
     1045            <warning>
     1046              <title>Avoid mixing saved and unsaved objects</title>
     1047              <para>
     1048                The approch used for object identity may give us a problem if we mix objects
     1049                which hasn't been saved to the database, with objects loaded from the database.
     1050                Our recommendation is to avoid that, and save any objects to the database before
     1051                adding them to sets, maps or any other structure that uses the
     1052                <methodname>equals()</methodname> and <methodname>hashCode()</methodname> methods.
     1053              </para>
     1054              <para>
     1055                To be more specific, the problem arises because the following two rules for
     1056                hash codes are contradicting when the hash code is based on the database id:
     1057              </para>
     1058              <orderedlist>
     1059              <listitem>
     1060                <para>
     1061                The hash code of an object mustn't change.
     1062                </para>
     1063              </listitem>
     1064              <listitem>
     1065                <para>
     1066                Equal objects must have equal hash code.
     1067                </para>
     1068              </listitem>
     1069              </orderedlist>
     1070              <para>
     1071                For objects in the database, the hash code is based on the id. For new objects,
     1072                which doesn't have an id yet, we fall back to the system hash code. But, what
     1073                happens when we save the new object to the database? If nobody has asked for
     1074                the hash code it is safe to use the id, otherwise we must stick with the system
     1075                hash code. Now, imagine that we load the same object from the database in
     1076                another Hibernate session. What will now happen? The loaded object will have
     1077                it's hash code based on the id but the original object is still using the
     1078                system hash code, which most likely is not the same as the id. Yet, the
     1079                <methodname>equals()</methodname> method returns true. This is a violation
     1080                of the contract for the equals method. If these two objects are used in a set
     1081                it may cause unexpected behaviour. Therefore, do not put new objects in a
     1082                set, or other collection, that calls the <methodname>hashCode()</methodname>
     1083                method before the object is saved to the database.         
     1084              </para>
     1085            </warning>
     1086           
     1087            <para>
     1088            See also:
     1089            </para>
     1090            <itemizedlist>
     1091            <listitem>
     1092              <para>
     1093              "Hibernate in action", chapter 3.4 "Understanding object identity", page 87-90
     1094              </para>
     1095            </listitem>
     1096            <listitem>
     1097              <para>
     1098              "Hibernate in action", chapter 4.1.4 "The scope of object identity", page 119-121
     1099              </para>
     1100            </listitem>
     1101            <listitem>
     1102              <para>
     1103              "Hibernate in action", chapter 4.1.6 "Implementing equals() and hashCode(), page 122-126
     1104              </para>
     1105            </listitem>
     1106            <listitem>
     1107              <para>
     1108              Hibernate reference documentation: <ulink
     1109                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/persistent-classes.html#persistent-classes-equalshashcode">4.3. Implementing equals() and hashCode()</ulink>
     1110              </para>
     1111            </listitem>
     1112            </itemizedlist>
     1113
     1114          </listitem>
     1115        </varlistentry>
     1116       
     1117        <varlistentry>
     1118          <term>No final methods</term>
     1119          <listitem>
     1120            <para>
     1121              No methods should be tagged with the <code>final</code> keyword. This is a
     1122              requirement to be able to use the proxy feature of Hibernate, which we need for
     1123              performance reasons.
     1124            </para>
     1125   
     1126            <para>
     1127            See also:
     1128            </para>
     1129            <itemizedlist>
     1130            <listitem>
     1131              <para>
     1132              Hibernate reference documentation: <ulink
     1133                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/persistent-classes.html#persistent-classes-pojo-final">4.1.3. Prefer non-final classes</ulink>
     1134              </para>
     1135            </listitem>
     1136            <listitem>
     1137              <para>
     1138              Hibernate reference documentation: <ulink
     1139                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/performance.html#performance-fetching-proxies">21.1.3. Single-ended association proxies</ulink>
     1140              </para>
     1141            </listitem>
     1142            </itemizedlist>
     1143          </listitem>
     1144        </varlistentry>
     1145
     1146
     1147        <varlistentry>
     1148          <term>Second-level cache</term>
     1149          <listitem>
     1150            <para>
     1151              To gain performance we use the second-level cache of Hibernate. It is a transparent
     1152              feature that doesn't affect the code in any way. The second-level cache is configured
     1153              in the <filename>hibernate.cfg.xml</filename> and <filename>ehcache.xml</filename>
     1154              configuration files and not in the individual class mapping files. BASE is shipped
     1155              with a standard configuration, but different deployment scenarios may have to fine-tune the cache
     1156              settings for that particular hardware/software setup. It is beyond the scope of
     1157              this document to discuss this issue.
     1158            </para>
     1159            <para>
     1160              The second-level cache is suitable for objects that are rarely modified but
     1161              are often needed. For example, we do not expect the user information represented
     1162              by the <classname docapi="net.sf.basedb.core.data">UserData</classname> object to
     1163              change very often, but it is displayed all the time as the owner of various items.
     1164              Before coming up with a good caching strategy we have to answer the following questions:
     1165            </para>
     1166           
     1167            <orderedlist>
     1168            <listitem>
     1169              <para>
     1170              Should objects of this class be cached at all?
     1171              </para>
     1172            </listitem>
     1173            <listitem>
     1174              <para>
     1175              How long timeout should we use?
     1176              </para>
     1177            </listitem>
     1178            <listitem>
     1179              <para>
     1180              How many objects should we keep in memory or on disk?
     1181              </para>
     1182            </listitem>
     1183            </orderedlist>
     1184
     1185            <para>
     1186              The first question is the most important. Good candidates are classes with few
     1187              objects that change rarely, but are read often. Also, objects which are linked
     1188              to by many other objects are good candidates. The <classname docapi="net.sf.basedb.core.data">UserData</classname>
     1189              class is an example which matches all three requirements. The <classname docapi="net.sf.basedb.core.data">TagData</classname>
     1190              class is an example which fulfils the first two. The <classname docapi="net.sf.basedb.core.data">BioMaterialEventData</classname>
     1191              class is on the other hand a bad cache candidate, since it is not linked to any
     1192              other object than a <classname docapi="net.sf.basedb.core.data">BioMaterialData</classname> object.
     1193            </para>
     1194            <para>
     1195              The answer to the second question depends on how often an object is modified.
     1196              For most objects this time is probably several days or months, but we would
     1197              not gain much by keeping objects in the cache for so long. Suddenly, the
     1198              information has changed and we won't risk that old information is kept that
     1199              long. We have set the timeout to 1 hour for all classes so far, and we don't
     1200              recommend a longer timeout. The only exception is for immutable objects, that
     1201              cannot be changed at all, which may have an infinite timeout.
     1202            </para>
     1203            <para>
     1204              The answer to the third question depends a lot on the hardware (available memory).
     1205              With lots of memory we can afford to cache more objects. Caching to disk is not
     1206              really necessary if the database is on the same machine as the web server, but
     1207              if it is on another machine we have to consider the network delay to connect
     1208              to the database versus the disk access time. The default configuration does not
     1209              use disk cache.
     1210            </para>
     1211
     1212            <para>
     1213            See also:
     1214            </para>
     1215            <itemizedlist>
     1216            <listitem>
     1217              <para>
     1218              "Hibernate in action", chapter 5.3 "Caching theory and practice", page 175-194.
     1219              </para>
     1220            </listitem>
     1221            <listitem>
     1222              <para>
     1223                Hibernate reference documentation: <ulink
     1224                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/performance.html#performance-cache">21.2. The Second Level Cache</ulink>
     1225              </para>
     1226            </listitem>
     1227            </itemizedlist>
     1228           
     1229          </listitem>
     1230        </varlistentry>
     1231
     1232        <varlistentry>
     1233          <term>Proxies</term>
     1234          <listitem>
     1235            <para>
     1236              Proxies are also used to gain performance, and they may have some impact on
     1237              the code. Proxies are created at runtime (by Hibernate) as a subclass of the
     1238              actual class but are not populated with data until some method of the object
     1239              is called. The data is loaded from the database the first time a method other
     1240              than <methodname>getId()</methodname> is called. Thus, we can avoid loading
     1241              data that is not needed at a particular time.
     1242            </para>
     1243       
     1244            <para>
     1245              There can be a problem with using the <code>instanceof</code> operator with proxies
     1246              and the table-per-class-hierarchy mapping. For example, if we have the abstract
     1247              class <classname>Animal</classname> and subclasses <classname>Cat</classname>
     1248              and <classname>Dog</classname>. The proxy of an <classname>Animal</classname> is a
     1249              runtime generated subclass of <classname>Animal</classname>, since we do not know if it
     1250              is a <classname>Cat</classname> or <classname>Dog</classname>. So,
     1251              <code>x instanceof Dog</code> and <code>x instanceof Cat</code> would both return
     1252              false. If we hadn't used a proxy, at least one of them would always be true.
     1253            </para>
     1254       
     1255            <para>
     1256              Proxies are only used when a not-null object is linked with many-to-one or
     1257              one-to-one from another object. If we ask for a specific object by id, or by a
     1258              query, we will never get a proxy. Therefore, it only makes sense to enable
     1259              proxies for classes that can be linked from other classes. One-to-one links on
     1260              the primary key where null is allowed silently disables the proxy feature,
     1261              since Hibernate doesn't know if there is an object or not without querying
     1262              the database.
     1263            </para>
     1264            <bridgehead>Proxy vs. cache</bridgehead>
     1265            <para>
     1266              The goal of a proxy and the second-level cache are the same: to avoid hitting the
     1267              database. It is perfectly possible to enable both proxies and the cache for a
     1268              class. Then we would start with a proxy and as soon as a method is called Hibernate
     1269              would look in the second-level cache. Only if it is not there it would be loaded
     1270              from the database. But, do we really need a proxy in the first place? Well, I think
     1271              it might be better to use only the cache or only proxies. But, this also makes it
     1272              even more important that the cache is configured correctly so there is a high
     1273              probability that the object is already in the cache.
     1274            </para>
     1275           
     1276            <para>
     1277              If a class has been configured to use the second-level cache, we recommend
     1278              that proxies are disabled. For child objects in a parent-child relationship proxies
     1279              should be disabled, since they have no other links to them than from the parent.
     1280              If a class can be linked as many-to-one from several other classes it makes sense
     1281              to enable proxies. If we have a long chain of many-to-one relations it may also make
     1282              sense to enable proxies at some level, even if the second-level cache is used.
     1283              In that case we only need to create one proxy instead of looking up several objects
     1284              in the cache. Also, think about how a particular class most commonly will be used
     1285              in a client application. For example, it is very common to display the name of the
     1286              owner of an item, but we are probably not interested in displaying quota
     1287              information for that user. So, it makes sense to put users in the second-level
     1288              cache and use proxies for quota information.
     1289            </para>
     1290
     1291            <warning>
     1292              <title>Batchable classes and stateless sessions</title>
     1293              <para>
     1294                Hibernate has a <emphasis>stateless session</emphasis> feature. A
     1295                stateless session has no first-level cache and doesn't use the second-level
     1296                cache either. This means that if we load an item with a stateless session
     1297                Hibernate will always traverse many-to-one and one-to-one associations and
     1298                load those objects as well, unless they are configured to use proxies.
     1299              </para>
     1300             
     1301              <para>
     1302                BASE use stateless sessions for loading <classname docapi="net.sf.basedb.core.data">BatchableData</classname>
     1303                items (reporters, raw data and features)
     1304                since they are many and we want to use as little memory as possible. Here it
     1305                is required that proxies are enabled for all items that are linked from any of
     1306                the batchable items, ie. <classname docapi="net.sf.basedb.core">RawBioAssay</classname>,
     1307                <classname docapi="net.sf.basedb.core">ReporterType</classname>,
     1308                <classname docapi="net.sf.basedb.core">ArrayDesignBlock</classname>, etc.
     1309                If we don't do this Hibernate will generate multiple additional select
     1310                statements for the same parent item which will affect performance
     1311                in a bad way.
     1312              </para>
     1313             
     1314              <para>
     1315                On the other hand, the proxies created from a stateless session cannot later
     1316                be initialised. We have to get the ID from the proxy and the load the object
     1317                using the regular session. But this can also results in lots of additional select
     1318                statements so if it is known before that we need some information it is recommended
     1319                that a FETCH JOIN query is used so that we get fully initialized objects instead of
     1320                proxies to begin with.
     1321              </para>
     1322            </warning>
     1323            <para>
     1324              Here is a table which summarises different settings for the second-level cache,
     1325              proxies, batch fetching and many-to-one links. Batch fetching and many-to-one links
     1326              are discussed later in this document.
     1327            </para>
     1328           
     1329            <para>
     1330              First, decide if the second-level cache should be enabled or not. Then, if
     1331              proxies should be enabled or not. The table then gives a reasonable setting for
     1332              the batch size and many-to-one mappings. NOTE! The many-to-one mappings are
     1333              the links from other classes to this one, not links from this class.
     1334            </para>
     1335           
     1336            <para>
     1337              The settings in this table are not absolute rules. In some cases there might
     1338              be a good reason for another combination. Please, write a comment about why
     1339              the recommendations were not followed.
     1340            </para>
     1341           
     1342            <table id="core_ref.rules.datalayer.cacheproxysettings">
     1343              <title>Choosing cache and proxy settings</title>
     1344              <tgroup cols="4">
     1345                <colspec colname="cache" />
     1346                <colspec colname="proxy" />
     1347                <colspec colname="batchsize" />
     1348                <colspec colname="outerjoin" />
     1349               
     1350                <thead>
     1351                  <row>
     1352                    <entry>Global configuration</entry>
     1353                    <entry namest="proxy" nameend="batchsize">Class mapping</entry>
     1354                    <entry>Many-to-one mapping</entry>
     1355                  </row>
     1356                  <row>
     1357                    <entry>Cache</entry>
     1358                    <entry>Proxy</entry>
     1359                    <entry>Batch-size</entry>
     1360                    <entry>Outer-join</entry>
     1361                  </row>
     1362                </thead>
     1363                <tbody>
     1364                  <row>
     1365                    <entry>no</entry>
     1366                    <entry>no*</entry>
     1367                    <entry>yes</entry>
     1368                    <entry>true</entry>
     1369                  </row>
     1370                  <row>
     1371                    <entry>yes</entry>
     1372                    <entry>no*</entry>
     1373                    <entry>no</entry>
     1374                    <entry>false</entry>
     1375                  </row>
     1376                  <row>
     1377                    <entry>no</entry>
     1378                    <entry>yes</entry>
     1379                    <entry>yes</entry>
     1380                    <entry>false</entry>
     1381                  </row>
     1382                  <row>
     1383                    <entry>yes</entry>
     1384                    <entry>yes</entry>
     1385                    <entry>no</entry>
     1386                    <entry>false</entry>
     1387                  </row>
     1388                </tbody>
     1389              </tgroup>
     1390            </table>
     1391           
     1392            <para>
     1393              * = Do not use this setting for classes which are many-to-one linked from a batchable
     1394              class.
     1395            </para>
     1396           
     1397            <para>
     1398            See also:
     1399            </para>
     1400            <itemizedlist>
     1401            <listitem>
     1402              <para>
     1403              "Hibernate in action", chapter 4.4.6 "Selecting a fetching strategy in mappings", page 146-147
     1404              </para>
     1405            </listitem>
     1406            <listitem>
     1407              <para>
     1408              "Hibernate in action", chapter 6.4.1 "Polymorphic many-to-one associations", page 234-236
     1409              </para>
     1410            </listitem>
     1411            <listitem>
     1412              <para>
     1413              Hibernate reference documentation: <ulink
     1414                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/performance.html#performance-fetching-proxies">21.1.3. Single-ended association proxies</ulink>
     1415              </para>
     1416            </listitem>
     1417            </itemizedlist>
     1418           
     1419          </listitem>
     1420        </varlistentry>
     1421
     1422        <varlistentry>
     1423          <term>Hibernate mappings</term>
     1424          <listitem>
     1425            <para>
     1426              We use Javadoc tags to specify the database mapping needed by Hibernate.
     1427              The tags are processed by XDoclet at build time which generates the XML-based
     1428              Hibernate mapping files.
     1429            </para>
     1430           
     1431            <note>
     1432              <title>XDoclet doesn't support all mappings</title>
     1433              <para>
     1434              The XDoclet that we use was developed to generate mapping files for
     1435              Hibernate 2.x. Since then, Hibernate has released several 3.x versions,
     1436              and the mapping file structure has changed. Some changes can be handled by
     1437              generating a corresponding 2.x mapping and then converting it to a 3.x
     1438              mapping at build time using simple search-and-replace operations.
     1439              One such case is to update the DTD reference to the 3.0 version instead of
     1440              the 2.0 version. Other changes can't use this approach. Instead we have to
     1441              provide extra mappings inside an XML files. This is also needed if we need
     1442              to use some of the new 3.x features that has no 2.x counterpart.
     1443              </para>
     1444            </note>
     1445          </listitem>
     1446        </varlistentry>
     1447
     1448        <varlistentry>
     1449            <term>Class mapping</term>
     1450            <listitem>
     1451             
     1452              <programlisting language="java">
    8581453/**
    8591454   This class holds information about any data...
    8601455   @author Your name
    861    @version 2.0
     1456   @since 3.0
    8621457   @hibernate.class table="`Anys`" lazy="false" batch-size="10"
    863    @base.modified $Date: 2007-08-17 09:18:29 +0200 (Fri, 17 Aug 2007) $
    8641458*/
    8651459public class AnyData
     
    8691463}
    8701464</programlisting>
     1465
     1466            <para>
     1467              The class declaration must contain a <code>@hibernate.class</code> Javadoc entry
     1468              where Hibernate can find the name of the table where items of this type are stored.
     1469              The table name should generally be the same as the class name, without the ending
     1470              <code>Data</code> and in a plural form. For example <classname docapi="net.sf.basedb.core.data">UserData</classname>
     1471              → <code>Users</code>. The back-ticks (`) around the table name tells Hibernate
     1472              to enclose the name in whatever the actual database manager uses for such things
     1473              (back-ticks in MySQL, quotes for an ANSI-compatible database).
     1474            </para>
     1475           
     1476            <important>
     1477              <title>Always set the lazy attribute</title>
     1478              <para>
     1479                The <sgmltag class="attribute">lazy</sgmltag> attribute enables/disables
     1480                proxies for the class. Do not forget to specify this attribute since the
     1481                default value is true. If proxies are enabled, it may also make sense to
     1482                specify a <sgmltag class="attribute">batch-size</sgmltag> attribute. Then
     1483                Hibernate will load the specified number of items in each SELECT statement
     1484                instead of loading them one by one. It may also make sense to specify a
     1485                batch size when proxies are disabled, but then it would probably be even
     1486                better to use eager fetching by setting <code>outer-join="true"</code>
     1487                (see many-to-one mapping).
     1488              </para>
     1489 
     1490              <para>
     1491                Classes that are linked with a many-to-one association from a batchable
     1492                class must specify <code>lazy="true"</code>. Otherwise the stateless session
     1493                feature of Hibernate may result in a large number of SELECT:s for the same
     1494                item, or even circular loops if two or more items references each other.
     1495              </para>
     1496            </important>
     1497           
     1498            <important>
     1499              <title>Remember to enable the second-level cache</title>
     1500              <para>
     1501                Do not forget to configure settings for the second-level cache if this
     1502                should be enabled. This is done in the <filename>hibernate.cfg.xml</filename>
     1503                and <filename>ehcache.xml</filename>.
     1504              </para>
     1505            </important>
    8711506         
    872           <para>
    873             The class declaration must contain a <code>@hibernate.class</code> Javadoc entry
    874             where Hibernate can find the name of the table where items of this type are stored.
    875             The table name should generally be the same as the class name, without the ending
    876             <code>Data</code> and in a plural form. For example <classname docapi="net.sf.basedb.core.data">UserData</classname>
    877             --&gt; <code>Users</code>. The back-ticks (`) around the table name tells Hibernate
    878             to enclose the name in whatever the actual database manager uses for such things
    879             (back-ticks in MySQL, quotes for an ANSI-compatible database).
    880           </para>
    881          
    882           <important>
    883             <title>Specify a value for the lazy attribute</title>
    884             <para>
    885               The lazy attribute enables/disables proxies for the class. Do not forget
    886               to specify this attribute since the default value is true. If proxies are
    887               enabled, it may also make sense to specify a batch-size attribute. Then
    888               Hibernate will load the specified number of items in each SELECT statement
    889               instead of loading them one by one. It may also make sense to specify a
    890               batch size when proxies are disabled, but then it would probably be even
    891               better to use eager fetching by setting <code>outer-join="true"</code>
    892               (see many-to-one mapping).
    893             </para>
    894 
    895             <para>
    896               Classes that are linked with a many-to-one association from a batchable
    897               class must specify <code>lazy="true"</code>. Otherwise the stateless session
    898               feature of Hibernate may result in a large number of SELECT:s for the same
    899               item, or even circular loops if two or more items references each other.
    900             </para>
    901           </important>
    902          
    903           <important>
    904             <title>Remember to enable the second-level cache</title>
    905             <para>
    906               Do not forget to configure settings for the second-level cache if this
    907               should be enabled. This is done in the <filename>hibernate.cfg.xml</filename>
    908               and <filename>ehcache.xml</filename>.
    909             </para>
    910           </important>
    911        
    912           <para>
    913           See also:
    914           </para>
    915          
    916           <itemizedlist>
    917           <listitem>
    918             <para>
    919             "Hibernate in action", chapter 3.3 "Defining the mapping metadata", page 75-87
    920             </para>
    921           </listitem>
    922           <listitem>
    923             <para>
    924             Hibernate user documentation: <ulink
    925               url="http://www.hibernate.org/hib_docs/reference/en/html/mapping.html#mapping-declaration-class">5.1.3. class</ulink>
    926             </para>
    927           </listitem>
    928           </itemizedlist>
    929          
    930         </simplesect>
    931        
    932         <simplesect id="core_ref.rules.datalayer.property">
    933           <title>Property mappings</title>
    934          
    935           <para>
    936             Properties such as strings, integers, dates, etc. are mapped with
    937             the <code>@hibernate.property</code> Javadoc tag. The main purpose
    938             is to define the database column name. The column names should
    939             generally be the same as the get/set method name without the get/set prefix,
    940             and with upper-case letters converted to lower-case and an underscore inserted.
    941             Examples:
    942           </para>
    943          
    944           <itemizedlist>
    945           <listitem>
    946             <para>
    947               <methodname>getAddress()</methodname>
    948               --&gt; <code>column="`address`"</code>
    949             </para>
    950           </listitem>
    951           <listitem>
    952             <para>
    953               <methodname>getLoginComment()</methodname>
    954               --&gt; <code>column="`login_comment`"</code>
    955             </para>
    956           </listitem>
    957           </itemizedlist>
    958          
    959           <para>
    960             The back-ticks (`) around the column name tells Hibernate to enclose
    961             the name in whatever the actual database manager uses for such things
    962             (back-ticks in MySQL, quotes for an ANSI-compatible database).
    963           </para>
    964          
    965           <bridgehead>String properties</bridgehead>
    966          
    967           <programlisting language="java">
     1507            <para>
     1508            See also:
     1509            </para>
     1510           
     1511            <itemizedlist>
     1512            <listitem>
     1513              <para>
     1514              "Hibernate in action", chapter 3.3 "Defining the mapping metadata", page 75-87
     1515              </para>
     1516            </listitem>
     1517            <listitem>
     1518              <para>
     1519              Hibernate reference documentation: <ulink
     1520                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-declaration-class">5.1.3. Entity</ulink>
     1521              </para>
     1522            </listitem>
     1523            </itemizedlist>
     1524           
     1525          </listitem>
     1526        </varlistentry>
     1527
     1528        <varlistentry>
     1529          <term>Property mappings</term>
     1530          <listitem>
     1531            <para>
     1532              Properties such as strings, integers, dates, etc. are mapped with
     1533              the <code>@hibernate.property</code> Javadoc tag. The main purpose
     1534              is to define the database column name. The column names should
     1535              generally be the same as the get/set method name without the get/set prefix,
     1536              and with upper-case letters converted to lower-case and an underscore inserted.
     1537              Examples:
     1538            </para>
     1539           
     1540            <itemizedlist>
     1541            <listitem>
     1542              <para>
     1543                <methodname>getAddress()</methodname>
     1544                → <code>column="`address`"</code>
     1545              </para>
     1546            </listitem>
     1547            <listitem>
     1548              <para>
     1549                <methodname>getLoginComment()</methodname>
     1550                → <code>column="`login_comment`"</code>
     1551              </para>
     1552            </listitem>
     1553            </itemizedlist>
     1554
     1555            <para>
     1556              The back-ticks (`) around the column name tells Hibernate to enclose
     1557              the name in whatever the actual database manager uses for such things
     1558              (back-ticks in MySQL, quotes for an ANSI-compatible database).
     1559            </para>
     1560           
     1561            <bridgehead>String properties</bridgehead>
     1562            <programlisting language="java">
    9681563public static int long MAX_STRINGPROPERTY_LENGTH = 255;
    9691564private String stringProperty;
     
    9831578</programlisting>
    9841579
    985           <para>
    986             Do not use a greater value than 255 for the length attribute. Some databases
    987             has that as the maximum length for character columns (ie. MySQL). If you need
    988             to store longer texts use <code>type="text"</code> instead. You can then skip
    989             the length attribute. Most databases will allow up to 65535 characters or more
    990             in a text field. Do not forget to specify the <code>not-null</code> attribute.
    991           </para>
    992          
    993           <para>
    994             You should also define a public constant <constant>MAX_STRINGPROPERTY_LENGTH</constant>
    995             containing the maximum allowed length of the string.
    996           </para>
    997          
    998           <bridgehead>Numerical properties</bridgehead>
    999          
    1000           <programlisting language="java">
     1580            <para>
     1581              Do not use a greater value than 255 for the <sgmltag class="attribute">length</sgmltag>
     1582              attribute. Some databases has that as the maximum length for character columns (ie. MySQL).
     1583              If you need to store longer texts use <code>type="text"</code> instead. You can then skip
     1584              the length attribute. Most databases will allow up to 65535 characters or more
     1585              in a text field. Do not forget to specify the <sgmltag class="attribute">not-null</sgmltag> attribute.
     1586            </para>
     1587           
     1588            <para>
     1589              You should also define a public constant <constant>MAX_STRINGPROPERTY_LENGTH</constant>
     1590              containing the maximum allowed length of the string.
     1591            </para>
     1592
     1593            <bridgehead>Numerical properties</bridgehead>
     1594           
     1595            <programlisting language="java">
    10011596private int intProperty;
    10021597/**
     
    10141609</programlisting>
    10151610
    1016           <para>
    1017             It is also possible to use <classname>Integer</classname>, <classname>Long</classname>
    1018             or <classname>Float</classname> objects instead of <classname>int</classname>,
    1019             <classname>long</classname> and <classname>float</classname>. We have only used it
    1020             if null values have some meaning.
    1021           </para>
    1022 
    1023         <bridgehead>Boolean properties</bridgehead>
    1024         <programlisting language="java">
     1611            <para>
     1612              It is also possible to use <classname>Integer</classname>, <classname>Long</classname>
     1613              or <classname>Float</classname> objects instead of <classname>int</classname>,
     1614              <classname>long</classname> and <classname>float</classname>. We have only used it
     1615              if null values have some meaning.
     1616            </para>
     1617           
     1618            <bridgehead>Boolean properties</bridgehead>
     1619            <programlisting language="java">
    10251620private boolean booleanProperty;
    10261621/**
     
    10381633}
    10391634</programlisting>
    1040         <para>
    1041           It is also possible to use a <classname>Boolean</classname> object instead of
    1042           <classname>boolean</classname>. It is only required if you absolutely need
    1043           null values to handle special cases.
    1044         </para>
    1045        
    1046         <bridgehead>Date values</bridgehead>
    1047        
    1048         <programlisting language="java">
     1635            <para>
     1636              It is also possible to use a <classname>Boolean</classname> object instead of
     1637              <classname>boolean</classname>. It is only required if you absolutely need
     1638              null values to handle special cases.
     1639            </para>
     1640
     1641            <bridgehead>Date values</bridgehead>
     1642           
     1643            <programlisting language="java">
    10491644private Date dateProperty;
    10501645/**
     
    10621657</programlisting>
    10631658       
    1064         <para>
    1065           Hibernate defines several other date and time types. We have decided to use
    1066           the <code>type="date"</code> type when we are only interested in the date and
    1067           the <code>type="timestamp"</code> when we are interested in both the date
    1068           and time.
    1069         </para>
    1070        
    1071         <para>
    1072         See also:
    1073         </para>
    1074        
    1075         <itemizedlist>
    1076           <listitem>
    1077             <para>
    1078             "Hibernate in action", chapter 3.3.2 "Basic property and class mappings", page 78-84
    1079             </para>
    1080           </listitem>
    1081           <listitem>
    1082             <para>
    1083             "Hibernate in action", chapter 6.1.1 "Built-in mapping types", page 198-200
    1084             </para>
    1085           </listitem>
    1086           <listitem>
    1087             <para>
    1088             Hibernate user documentation: <ulink
    1089               url="http://www.hibernate.org/hib_docs/reference/en/html/mapping.html#mapping-declaration-property">5.1.9. property</ulink>
    1090             </para>
    1091           </listitem>
    1092           <listitem>
    1093             <para>
    1094             Hibernate user documentation: <ulink
    1095               url="http://www.hibernate.org/hib_docs/reference/en/html/mapping.html#mapping-types-basictypes">5.2.2. Basic value types</ulink>
    1096             </para>
    1097           </listitem>
    1098           </itemizedlist>
     1659          <para>
     1660            Hibernate defines several other date and time types. We have decided to use
     1661            the <code>type="date"</code> type when we are only interested in the date and
     1662            the <code>type="timestamp"</code> when we are interested in both the date
     1663            and time.
     1664          </para>
    10991665         
    1100         </simplesect>
    1101        
    1102         <simplesect id="core_ref.rules.datalayer.manytoone">
    1103           <title>Many-to-one mappings</title>
     1666          <para>
     1667          See also:
     1668          </para>
    11041669         
    1105           <programlisting language="java">
     1670          <itemizedlist>
     1671            <listitem>
     1672              <para>
     1673              "Hibernate in action", chapter 3.3.2 "Basic property and class mappings", page 78-84
     1674              </para>
     1675            </listitem>
     1676            <listitem>
     1677              <para>
     1678              "Hibernate in action", chapter 6.1.1 "Built-in mapping types", page 198-200
     1679              </para>
     1680            </listitem>
     1681            <listitem>
     1682              <para>
     1683              Hibernate reference documentation: <ulink
     1684                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-declaration-property">5.1.4. property</ulink>
     1685              </para>
     1686            </listitem>
     1687            <listitem>
     1688              <para>
     1689              Hibernate reference documentation: <ulink
     1690                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-types-basictypes">5.2.2. Basic value types</ulink>
     1691              </para>
     1692            </listitem>
     1693            </itemizedlist>
     1694               
     1695          </listitem>
     1696        </varlistentry>
     1697
     1698        <varlistentry id="core_ref.rules.datalayer.manytoone">
     1699          <term>Many-to-one mappings</term>
     1700          <listitem>
     1701            <programlisting language="java">
    11061702private OtherData other;
    11071703/**
     
    11191715</programlisting>
    11201716         
    1121         <para>
    1122           We create a many-to-one mapping with the <code>@hibernate.many-to-one</code> tag.
    1123           The most important attribute is the <code>column</code> attribute which specifies the name of
    1124           the database column to use for the id of the other item. The back-ticks (`)
    1125           around the column name tells Hibernate to enclose the name in whatever the
    1126           actual database manager uses for such things (back-ticks in MySQL, quotes for
    1127           an ANSI-compatible database).
    1128         </para>
    1129        
    1130         <para>
    1131           We also recommend that the <code>not-null</code> attribute is specified. Hibernate
    1132           will not check for null values, but it will generate table columns that allow
    1133           or disallow null values. See it as en extra safety feature while debugging.
    1134           It is also used to determine if Hibernate uses <code>LEFT JOIN</code> or
    1135           <code>INNER JOIN</code> in SQL statements.
    1136         </para>
    1137        
    1138         <para>
    1139           The <code>outer-join</code> attribute is important and affects how the
    1140           cache and proxies are used. It can take three values: <constant>auto</constant>,
    1141           <constant>true</constant> or <constant>false</constant>. If the value is
    1142           <constant>true</constant> Hibernate will always use a join to load the linked
    1143           object in a single select statement, overriding the cache and proxy settings.
    1144           This value should only be used if the class being linked has disabled both
    1145           proxies and the second-level cache, or if it is a link between a child
    1146           and parent in a parent-child relationship. A false value is best when
    1147           we expect the associated object to be in the second-level cache or proxying
    1148           is enabled. This is probably the most common case. The auto setting uses a
    1149           join if proxying is disabled otherwise it uses a proxy. Since we always
    1150           know if proxying is enabled or not, this setting is not very useful. See
    1151           <xref linkend="core_ref.rules.datalayer.cacheproxysettings" /> for the
    1152           recommended settings.
    1153         </para>
    1154        
    1155         <para>
    1156           See also:
    1157         </para>
    1158          
    1159         <itemizedlist>
    1160           <listitem>
    1161             <para>
    1162             "Hibernate in action", chapter 3.7 "Introducing associations", page 105-112
    1163             </para>
    1164           </listitem>
    1165           <listitem>
    1166             <para>
    1167             "Hibernate in action", chapter 4.4.5-4.4.6 "Fetching strategies", page 143-151
    1168             </para>
    1169           </listitem>
    1170           <listitem>
    1171             <para>
    1172             "Hibernate in action", chapter 6.4.1 "Polymorphic many-to-one associations", page 234-236
    1173             </para>
    1174           </listitem>
    1175           <listitem>
    1176             <para>
    1177             Hibernate user documentation: <ulink
    1178               url="http://www.hibernate.org/hib_docs/reference/en/html/mapping.html#mapping-declaration-manytoone">5.1.10. many-to-one</ulink>
    1179             </para>
    1180           </listitem>
    1181           </itemizedlist>
    1182          
    1183         </simplesect>
    1184        
    1185         <simplesect id="core_ref.rules.datalayer.manytomany">
    1186           <title>Many-to-many and one-to-many mappings</title>
    1187          
    11881717          <para>
    1189             There are many variants of mapping many-to-many or one-to-many, and it is
    1190             not possible to give examples of all of them. In the code these mappings
    1191             are represented by <classname>Set</classname>:s, <classname>Map</classname>:s,
    1192             <classname>List</classname>:s, or some other collection object. The most
    1193             important thing to remember is that (in our application) the collections
    1194             are only used to maintain the links between objects. They are not used
    1195             for returning objects to client applications, as is the case with the
    1196             many-to-one mapping.
     1718            We create a many-to-one mapping with the <code>@hibernate.many-to-one</code> tag.
     1719            The most important attribute is the <code>column</code> attribute which specifies the name of
     1720            the database column to use for the id of the other item. The back-ticks (`)
     1721            around the column name tells Hibernate to enclose the name in whatever the
     1722            actual database manager uses for such things (back-ticks in MySQL, quotes for
     1723            an ANSI-compatible database).
    11971724          </para>
    11981725         
    11991726          <para>
    1200             For example, if we want to find all members of a group we do not use the
    1201             <code>GroupData.getUsers()</code> method, instead we will execute a database query
    1202             to retrieve them. The reason for this design is that the logged in user may
    1203             not have access to all users and we must add a permission checking filter
    1204             before returning the user objects to the client application. Using a query
    1205             will also allow client applications to specify sorting and filtering options
    1206             for the users that are returned.
     1727            We also recommend that the <sgmltag class="attribute">not-null</sgmltag> attribute
     1728            is specified. Hibernate will not check for null values, but it will generate table
     1729            columns that allow or disallow null values. See it as en extra safety feature while debugging.
     1730            It is also used to determine if Hibernate uses <code>LEFT JOIN</code> or
     1731            <code>INNER JOIN</code> in SQL statements.
    12071732          </para>
    12081733         
    1209           <programlisting language="java">
     1734          <para>
     1735            The <sgmltag class="attribute">outer-join</sgmltag> attribute is important and affects how the
     1736            cache and proxies are used. It can take three values: <constant>auto</constant>,
     1737            <constant>true</constant> or <constant>false</constant>. If the value is
     1738            <constant>true</constant> Hibernate will always use a join to load the linked
     1739            object in a single select statement, overriding the cache and proxy settings.
     1740            This value should only be used if the class being linked has disabled both
     1741            proxies and the second-level cache, or if it is a link between a child
     1742            and parent in a parent-child relationship. A <constant>false</constant> value is best when
     1743            we expect the associated object to be in the second-level cache or proxying
     1744            is enabled. This is probably the most common case. The auto setting uses a
     1745            join if proxying is disabled otherwise it uses a proxy. Since we always
     1746            know if proxying is enabled or not, this setting is not very useful. See
     1747            <xref linkend="core_ref.rules.datalayer.cacheproxysettings" /> for the
     1748            recommended settings.
     1749          </para>
     1750         
     1751          <para>
     1752            See also:
     1753          </para>
     1754           
     1755          <itemizedlist>
     1756            <listitem>
     1757              <para>
     1758              "Hibernate in action", chapter 3.7 "Introducing associations", page 105-112
     1759              </para>
     1760            </listitem>
     1761            <listitem>
     1762              <para>
     1763              "Hibernate in action", chapter 4.4.5-4.4.6 "Fetching strategies", page 143-151
     1764              </para>
     1765            </listitem>
     1766            <listitem>
     1767              <para>
     1768              "Hibernate in action", chapter 6.4.1 "Polymorphic many-to-one associations", page 234-236
     1769              </para>
     1770            </listitem>
     1771            <listitem>
     1772              <para>
     1773              Hibernate reference documentation: <ulink
     1774                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#d0e7576">5.1.7. Mapping one to one and many to one associations</ulink>
     1775              </para>
     1776            </listitem>
     1777            </itemizedlist>
     1778          </listitem>
     1779        </varlistentry>
     1780
     1781        <varlistentry id="core_ref.rules.datalayer.manytomany">
     1782          <term>Many-to-many and one-to-many mappings</term>
     1783          <listitem>
     1784            <para>
     1785              There are many variants of mapping many-to-many or one-to-many, and it is
     1786              not possible to give examples of all of them. In the code these mappings
     1787              are represented by <classname>Set</classname>:s, <classname>Map</classname>:s,
     1788              <classname>List</classname>:s, or some other collection object. The most
     1789              important thing to remember is that (in our application) the collections
     1790              are only used to maintain the links between objects. They are (in most cases)
     1791              not used for returning objects to client applications, as is the case with the
     1792              many-to-one mapping.
     1793            </para>
     1794           
     1795            <para>
     1796              For example, if we want to find all members of a group we do not use the
     1797              <code>GroupData.getUsers()</code> method, instead we will execute a database query
     1798              to retrieve them. The reason for this design is that the logged in user may
     1799              not have access to all users and we must add a permission checking filter
     1800              before returning the user objects to the client application. Using a query
     1801              will also allow client applications to specify sorting and filtering options
     1802              for the users that are returned.
     1803            </para>
     1804            <programlisting language="java">
     1805<![CDATA[
    12101806// RoleData.java
    1211 private Set&lt;UserData&gt; users;
     1807private Set<UserData> users;
    12121808/**
    1213    Many-to-many from roles to users
     1809   Many-to-many from roles to users.
    12141810   @hibernate.set table="`UserRoles`" lazy="true"
    12151811   @hibernate.collection-key column="`role_id`"
     
    12171813      class="net.sf.basedb.core.data.UserData"
    12181814*/
    1219 public Set&lt;UserData&gt; getUsers()
    1220 {
    1221    if (users == null) users = new HashSet&lt;UserData&gt;();
     1815public Set<UserData> getUsers()
     1816{
     1817   if (users == null) users = new HashSet<UserData>();
    12221818   return users;
    12231819}
     
    12261822   this.users = users;
    12271823}
    1228 </programlisting>
    1229          
    1230           <para>
    1231             As you can see this mapping is a lot more complicated than what we have
    1232             seen before. The most important thing is the <code>lazy</code> attribute.
    1233             It tells Hibernate to delay the loading of the related objects until the set
    1234             is accessed. If the value is false or missing, Hibernate will load all objects
    1235             immediately. There is almost never a good reason to specify something other
    1236             than <code>lazy="true"</code>.
    1237           </para>
    1238          
    1239           <para>
    1240             Another important thing to remember is that the get method must always return
    1241             the same object that Hibernate passed to the set method. Otherwise, Hibernate
    1242             will not be able to detect changes made to the collection and as a result
    1243             will have to delete and then recreate all links. To ensure that the collection
    1244             object is not changed we have made the <methodname>setUsers()</methodname> method
    1245             package private, and the <methodname>getUsers()</methodname> will create a
    1246             new <classname>HashSet</classname> for us only if Hibernate didn't pass one
    1247             in the first place.
    1248           </para>
    1249          
    1250           <para>
    1251             Let's also have a look at the reverse mapping:
    1252           </para>
    1253          
    1254           <programlisting language="java">
     1824]]>
     1825</programlisting>
     1826            <para>
     1827              As you can see this mapping is a lot more complicated than what we have
     1828              seen before. The most important thing is the <sgmltag class="attribute">lazy</sgmltag>
     1829              attribute. It tells Hibernate to delay the loading of the related objects until the set
     1830              is accessed. If the value is false or missing, Hibernate will load all objects
     1831              immediately. There is almost never a good reason to specify something other
     1832              than <code>lazy="true"</code>.
     1833            </para>
     1834           
     1835            <para>
     1836              Another important thing to remember is that the getter method must always return
     1837              the same object that Hibernate passed to the setter method. Otherwise, Hibernate
     1838              will not be able to detect changes made to the collection and as a result
     1839              will have to delete and then recreate all links. To ensure that the collection
     1840              object is not changed we have made the <methodname>setUsers()</methodname> method
     1841              package private, and the <methodname>getUsers()</methodname> will create a
     1842              new <classname>HashSet</classname> for us only if Hibernate didn't pass one
     1843              in the first place.
     1844            </para>
     1845            <para>
     1846              Let's also have a look at the reverse mapping:
     1847            </para>
     1848           
     1849            <programlisting language="java">
     1850<![CDATA[
    12551851// UserData.java
    1256 private Set&lt;RoleData&gt; roles;
     1852private Set<RoleData> roles;
    12571853/**
    12581854   Many-to-many from users to roles
     
    12621858      class="net.sf.basedb.core.data.RoleData"
    12631859*/
    1264 Set&lt;RoleData&gt; getRoles()
     1860Set<RoleData> getRoles()
    12651861{
    12661862   return roles;
    12671863}
    1268 void setRoles(Set&lt;RoleData&gt; roles)
     1864void setRoles(Set<RoleData> roles)
    12691865{
    12701866   this.roles = roles;
    12711867}
    1272 </programlisting>
    1273 
    1274           <para>
    1275             The only real difference here is that both the setter and the getter methods
    1276             are package private. This is required because Hibernate will get confused if
    1277             we modify both ends. Thus, we are forced to always add/remove users to/from
    1278             the set in the <classname docapi="net.sf.basedb.core.data">GroupData</classname> object. The methods in the
    1279             <classname docapi="net.sf.basedb.core.data">RoleData</classname> class are never used by us.
    1280             Note that we do not have to check for null and create a new set since Hibernate
    1281             will handle null values as an empty set.
    1282           </para>
     1868]]>
     1869</programlisting>
     1870            <para>
     1871              The only real difference here is that both the setter and the getter methods
     1872              are package private. This is a safety measure because Hibernate will get confused if
     1873              we modify both ends. Thus, we are forced to always add/remove users to/from
     1874              the set in the <classname docapi="net.sf.basedb.core.data">RoleData</classname> object. The methods in the
     1875              <classname docapi="net.sf.basedb.core.data">UserData</classname> class are never used by us.
     1876              Note that we do not have to check for null and create a new set since Hibernate
     1877              will handle null values as an empty set.
     1878            </para>
     1879            <para>
     1880              So, why do we need the second collection at all? It is never accessed
     1881              except by Hibernate, and since it is lazy it will always be "empty".
     1882              The answer is that we want to use the relation in HQL statements.
     1883              For example:
     1884            </para>
     1885           
     1886            <programlisting language="sql">
     1887SELECT ... FROM RoleData rle WHERE rle.users ...
     1888SELECT ... FROM UserData usr WHERE usr.roles ...
     1889</programlisting>
    12831890         
    1284           <para>
    1285             So, why do we need the second collection at all? It is never accessed
    1286             except by Hibernate, and since it is lazy it will always be "empty".
    1287             The answer is that we want to use the relation in HQL statements.
    1288             For example:
    1289           </para>
    1290          
    1291           <programlisting language="sql">
    1292 SELECT ... FROM GroupData grp WHERE grp.users ...
    1293 SELECT ... FROM UserData usr WHERE usr.groups ...
    1294 </programlisting>
    1295          
    1296           <para>
    1297             Without the inverse mapping, it would not have been possible to execute
    1298             the second HQL statement. The inverse mapping is also important in
    1299             parent-child relationships, where it is used to cascade delete the children
    1300             if a parent is deleted.
    1301           </para>
    1302 
    1303           <warning>
    1304             <title>Do not use the inverse="true" setting</title>
    1305             <para>
    1306               Hibernate defines an <code>inverse="true"</code> setting that can be used with
    1307               the <code>@hibernate.set</code> tag. If specified, Hibernate will ignore
    1308               changes made to that collection. However, there is one problem with specifying
    1309               this attribute. Hibernate doesn't delete entries in the association table,
    1310               leading to foreign key violations if we try to delete a user. The only
    1311               solutions are to skip the <code>inverse="true"</code> attribute or to
    1312               manually delete the object from all collections on the non-inverse end.
    1313               The first alternative is the most efficient since it only requires a
    1314               single SQL statement. The second alternative must first load all associated
    1315               objects and then issue a single delete statement for each association.
    1316             </para>
    1317            
    1318             <para>
    1319               In the "Hibernate in action" book they have a very different design
    1320               where they recommend that changes are made in both collections. We don't
    1321               have to do this since we are only interested in maintaining the links,
    1322               which is always done in one of the collections.
    1323             </para>
    1324           </warning>
    1325 
    1326           <bridgehead>Parent-child relationships</bridgehead>
    1327 
    1328           <para>
    1329             When one or more objects are tightly linked to some other object we talk
    1330             about a parent-child relationship. This kind of relationship becomes important
    1331             when we are about to delete a parent object. The children cannot exist
    1332             without the parent so they must also be deleted. Luckily, Hibernate can
    1333             do this for us if we specify a <code>cascade="delete"</code> option for the link.
    1334             This example is a one-to-many link between client and help texts.
    1335           </para>
    1336 
    1337           <programlisting language="java">
     1891            <para>
     1892              Without the second mapping, it would not have been possible to execute
     1893              the second HQL statement. The inverse mapping is also important in
     1894              parent-child relationships, where it is used to cascade delete the children
     1895              if a parent is deleted (see below).
     1896            </para>
     1897
     1898            <warning>
     1899              <title>Do not use the inverse="true" setting</title>
     1900              <para>
     1901                Hibernate defines an <code>inverse="true"</code> setting that can be used with
     1902                the <code>@hibernate.set</code> tag. If specified, Hibernate will ignore
     1903                changes made to that collection. However, there is one problem with specifying
     1904                this attribute. Hibernate doesn't delete entries in the association table,
     1905                leading to foreign key violations if we try to delete a user. The only
     1906                solutions are to skip the <code>inverse="true"</code> attribute or to
     1907                manually delete the object from all collections on the non-inverse end.
     1908                The first alternative is the most efficient since it only requires a
     1909                single SQL statement. The second alternative must first load all associated
     1910                objects and then issue a single delete statement for each association.
     1911              </para>
     1912             
     1913              <para>
     1914                In the "Hibernate in action" book they have a very different design
     1915                where they recommend that changes are made in both collections. We don't
     1916                have to do this since we are only interested in maintaining the links,
     1917                which is always done in one of the collections.
     1918              </para>
     1919            </warning>
     1920
     1921            <bridgehead>Parent-child relationships</bridgehead>
     1922 
     1923            <para>
     1924              When one or more objects are tightly linked to some other object we talk
     1925              about a parent-child relationship. This kind of relationship becomes important
     1926              when we are about to delete a parent object. The children cannot exist
     1927              without the parent so they must also be deleted. Luckily, Hibernate can
     1928              do this for us if we specify a <code>cascade="delete"</code> option for the link.
     1929              This example is a one-to-many link between client and help texts.
     1930            </para>
     1931
     1932            <programlisting language="java">
     1933<![CDATA[
    13381934// ClientData.java
    1339 private Set&lt;HelpData&gt; helpTexts;
     1935private Set<HelpData> helpTexts;
    13401936/**
    13411937   This is the inverse end.
     
    13451941   @hibernate.collection-one-to-many class="net.sf.basedb.core.data.HelpData"
    13461942*/
    1347 Set&lt;HelpData&gt; getHelpTexts()
     1943Set<HelpData> getHelpTexts()
    13481944{
    13491945   return helpTexts;
    13501946}
    13511947
    1352 void setHelpTexts(Set&lt;HelpData&gt; helpTexts)
     1948void setHelpTexts(Set<HelpData> helpTexts)
    13531949{
    13541950   this.helpTexts = helpTexts;
     
    13701966   this.client = client;
    13711967}
    1372 </programlisting>
    1373 
    1374           <para>
    1375             This show both sides of the one-to-many mapping between parent and children.
    1376             As you can see the <code>@hibernate.set</code> doesn't specify a table,
    1377             since it is given by the <code>class</code> attribute of the
    1378             <code>@hibernate.collection-one-to-many</code> tag.
    1379           </para>
    1380          
    1381           <para>
    1382             In a one-to-many mapping, it is always the "one" side that handles the
    1383             link so the "many" side should always be mapped with <code>inverse="true"</code>.
    1384           </para>
    1385 
    1386           <bridgehead>Maps</bridgehead>
    1387          
    1388           <para>
    1389             Another type of many-to-many mapping uses a <interfacename>Map</interfacename>
    1390             for the collection. This kind of mapping is needed when the association between
    1391             two objects needs additional data to be kept as part of the association.
    1392             For example, the permission (stored as an integer value) given to users that
    1393             are members of a project. Note that you should use a <interfacename>Set</interfacename>
    1394             for mapping the inverse end.
    1395           </para>
    1396          
    1397           <programlisting language="java">
     1968]]>
     1969</programlisting>
     1970            <para>
     1971              This show both sides of the one-to-many mapping between parent and children.
     1972              As you can see the <code>@hibernate.set</code> doesn't specify a table,
     1973              since it is given by the <code>class</code> attribute of the
     1974              <code>@hibernate.collection-one-to-many</code> tag.
     1975            </para>
     1976           
     1977            <para>
     1978              In a one-to-many mapping, it is always the "one" side that handles the
     1979              link so the "many" side should always be mapped with <code>inverse="true"</code>.
     1980            </para>
     1981
     1982            <bridgehead>Maps</bridgehead>
     1983           
     1984            <para>
     1985              Another type of many-to-many mapping uses a <interfacename>Map</interfacename>
     1986              for the collection. This kind of mapping is needed when the association between
     1987              two objects needs additional data to be kept as part of the association.
     1988              For example, the permission (stored as an integer value) given to users that
     1989              are members of a project. Note that you should use a <interfacename>Set</interfacename>
     1990              for mapping the inverse end.
     1991            </para>
     1992            <programlisting language="java">
     1993<![CDATA[
    13981994// ProjectData.java
    1399 private Map&lt;UserData, Integer&gt; users;
     1995private Map<UserData, Integer> users;
    14001996/**
    14011997   Many-to-many mapping between projects and users including permission values.
     
    14062002   @hibernate.collection-element column="`permission`" type="int" not-null="true"
    14072003*/
    1408 public Map&lt;UserData, Integer&gt; getUsers()
    1409 {
    1410    if (users == null) users = new HashMap&lt;UserData, Integer&gt;();
     2004public Map<UserData, Integer> getUsers()
     2005{
     2006   if (users == null) users = new HashMap<UserData, Integer>();
    14112007   return users;
    14122008}
    1413 void setUsers(Map&lt;UserData, Integer&gt; users)
     2009void setUsers(Map<UserData, Integer> users)
    14142010{
    14152011   this.users = users;
     
    14172013
    14182014// UserData.java
    1419 private Set&lt;ProjectData&gt; projects;
     2015private Set<ProjectData> projects;
    14202016/**
    14212017   This is the inverse end.
     
    14262022      class="net.sf.basedb.core.data.ProjectData"
    14272023*/
    1428 Set&lt;ProjectData&gt; getProjects()
     2024Set<ProjectData> getProjects()
    14292025{
    14302026   return projects;
    14312027}
    1432 void setProjects(Set&lt;ProjectData&gt; projects)
     2028void setProjects(Set<ProjectData> projects)
    14332029{
    14342030   this.projects = projects;
    14352031}
    1436 </programlisting>
    1437        
    1438         <para>
    1439           See also:
    1440         </para>
    1441        
    1442         <itemizedlist>
    1443           <listitem>
    1444             <para>
    1445             "Hibernate in action", chapter 3.7 "Introducing associations", page 105-112
    1446             </para>
    1447           </listitem>
    1448           <listitem>
    1449             <para>
    1450             "Hibernate in action", chapter 6.2 "Mapping collections of value types", page 211-220
    1451             </para>
    1452           </listitem>
    1453           <listitem>
    1454             <para>
    1455             "Hibernate in action", chapter 6.3.2 "Many-to-many associations", page 225-233
    1456             </para>
    1457           </listitem>
    1458           <listitem>
    1459             <para>
    1460             Hibernate user documentation: <ulink
    1461               url="http://www.hibernate.org/hib_docs/reference/en/html/collections.html">Chapter 6. Collection Mapping</ulink>
    1462             </para>
    1463           </listitem>
    1464           <listitem>
    1465             <para>
    1466             Hibernate user documentation: <ulink
    1467               url="http://www.hibernate.org/hib_docs/reference/en/html/example-parentchild.html">Chapter 21. Example: Parent/Child</ulink>
    1468             </para>
    1469           </listitem>
    1470           </itemizedlist>
    1471        
    1472 
    1473         </simplesect>
    1474        
    1475         <simplesect id="core_ref.rules.datalayer.onetoone">
    1476           <title>One-to-one mappings</title>
    1477          
     2032]]>
     2033</programlisting>
    14782034          <para>
    1479             A one-to-one mapping can come in two different forms, depending on if both
    1480             objects should have the same id or not. We start with the case were the objects
    1481             can have different id:s and the link is done with an extra column in one of
    1482             the tables. The example is from the mapping between hybridizations and
    1483             arrayslides.
     2035            See also:
    14842036          </para>
    14852037         
    1486           <programlisting language="java">
    1487 // HybridizationData.java
     2038          <itemizedlist>
     2039            <listitem>
     2040              <para>
     2041              "Hibernate in action", chapter 3.7 "Introducing associations", page 105-112
     2042              </para>
     2043            </listitem>
     2044            <listitem>
     2045              <para>
     2046              "Hibernate in action", chapter 6.2 "Mapping collections of value types", page 211-220
     2047              </para>
     2048            </listitem>
     2049            <listitem>
     2050              <para>
     2051              "Hibernate in action", chapter 6.3.2 "Many-to-many associations", page 225-233
     2052              </para>
     2053            </listitem>
     2054            <listitem>
     2055              <para>
     2056              Hibernate reference documentation: <ulink
     2057                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html">Chapter 7. Collection Mapping</ulink>
     2058              </para>
     2059            </listitem>
     2060            <listitem>
     2061              <para>
     2062              Hibernate reference documentation: <ulink
     2063                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/example-parentchild.html">Chapter 24. Example: Parent/Child</ulink>
     2064              </para>
     2065            </listitem>
     2066            </itemizedlist>
     2067           
     2068          </listitem>
     2069        </varlistentry>
     2070
     2071        <varlistentry>
     2072          <term>One-to-one mappings</term>
     2073          <listitem>
     2074            <para>
     2075              A one-to-one mapping can come in two different forms, depending on if both
     2076              objects should have the same id or not. We start with the case were the objects
     2077              can have different id:s and the link is done with an extra column in one of
     2078              the tables. The example is from the mapping between physical bioassays and
     2079              arrayslides.
     2080            </para>
     2081
     2082            <programlisting language="java">
     2083// PhysicalBioAssayData.java
    14882084private ArraySlideData arrayslide;
    14892085/**
    14902086   Get the array slide
    1491    @hibernate.many-to-one column="`arrayslide_id`" not-null="false" unique="true"
     2087   @hibernate.many-to-one column="`arrayslide_id`" not-null="false"
     2088      unique="true" outer-join="false"
    14922089*/
    14932090public ArraySlideData getArraySlide()
     
    14972094public void setArraySlide(ArraySlideData arrayslide)
    14982095{
    1499    arrayslide.setHybridization(this);
    15002096   this.arrayslide = arrayslide;
    15012097}
    15022098
    15032099// ArraySlideData.java
    1504 private HybridizationData hybridization;
     2100private PhysicalBioAssayData bioassay;
    15052101/**
    1506    Get the hybridization
     2102   Get the bioassay.
    15072103   @hibernate.one-to-one property-ref="arraySlide"
    15082104*/
    1509 public HybridizationData getHybridization()
     2105public PhysicalBioAssayData getPhysicalBioAssay()
    15102106{
    15112107   return hybridization;
    15122108}
    1513 void setHybridization(HybridizationData hybridization)
    1514 {
    1515    this.hybridization = hybridization;
     2109public void setPhysicalBioAssay(PhysicalBioAssayData bioassay)
     2110{
     2111   this.bioassay = bioassay;
    15162112}         
    15172113</programlisting>
    1518          
    1519           <para>
    1520             As you can see, we use the many-to-one mapping on with a <code>unique="true"</code>
    1521             option for the hybridization. This will force the database to only allow the
    1522             same array slide to be linked once. Also note that since, <code>not-null="false"</code>,
    1523             null values are allowed and it doesn't matter which end of the relation that
    1524             is inserted first into the database.
    1525           </para>
    1526           <para>
    1527             For the array slide end we use a <code>@hibernate.one-to-one</code>
    1528             mapping and specify the name of the property on the other end that we are
    1529             linking to. Also, note that the we can only change the link with the
    1530             <methodname>HybridizationData.setArraySlide()</methodname> method, and that
    1531             this method also updates the other end.
    1532           </para>
    1533 
    1534           <para>
    1535             The second form of a one-to-one mapping is used when both objects must
    1536             have the same id (primary key). The example is from the mapping between users
    1537             and passwords.
    1538           </para>
    1539          
    1540           <programlisting language="java">
     2114            <para>
     2115              As you can see, we use the <code>@hibernate.many-to-one</code> mapping with <code>unique="true"</code>
     2116              for the bioassay side. This will force the database to only allow the
     2117              same array slide to be linked once. Also note that since, <code>not-null="false"</code>,
     2118              null values are allowed and it doesn't matter which end of the relation that
     2119              is inserted first into the database.
     2120            </para>
     2121            <para>
     2122              For the array slide end we use a <code>@hibernate.one-to-one</code>
     2123              mapping and specify the name of the property on the other end that we are
     2124              linking to. One important thing to remember is to keep both ends synchronized.
     2125              This should usually be done at the core layer and not in the data layer.
     2126              Doing it in the data layer may effectively disable lazy loading if the synchronization
     2127              code causes proxy initialization.
     2128            </para>
     2129
     2130            <para>
     2131              The second form of a one-to-one mapping is used when both objects must
     2132              have the same id (primary key). The example is from the mapping between users
     2133              and passwords.
     2134            </para>
     2135           
     2136            <programlisting language="java">
    15412137// UserData.java
    15422138/**
     
    15842180</programlisting>
    15852181         
    1586           <para>
    1587             In this case, we use the <code>@hibernate.one-to-one</code> mapping
    1588             in both classes. The <code>constrained="true"</code> tag in <classname docapi="net.sf.basedb.core.data">UserData</classname>
    1589             tells Hibernate to always insert the password first, and then the user. The makes it
    1590             possible to use the (auto-generated) id for the password as the id
    1591             for the user. This is controlled by the mapping for the <methodname>UserData.getId()</methodname>
    1592             method, which uses the <code>foreign</code> id generator. This generator will look
    1593             at the password property, ie. call <methodname>getPassword().getId()</methodname>
    1594             to find the id for the user. Also note the initialisation code and <code>cascade="all"</code>
    1595             tag in the <methodname>UserData.getPassword()</methodname> method. This is need
    1596             to avoid <classname>NullPointerException</classname>:s and to make sure everything
    1597             is created and deleted properly.
    1598           </para>
    1599          
    1600           <para>
    1601             See also:
    1602           </para>
    1603          
    1604         <itemizedlist>
    1605           <listitem>
    1606             <para>
    1607             "Hibernate in action", chapter 6.3.1 "One-to-one association", page 220-225
    1608             </para>
    1609           </listitem>
    1610           <listitem>
    1611             <para>
    1612             Hibernate user documentation: <ulink
    1613               url="http://www.hibernate.org/hib_docs/reference/en/html/mapping.html#mapping-declaration-onetoone">5.1.11. one-to-one</ulink>
    1614             </para>
    1615           </listitem>
    1616           </itemizedlist>
    1617          
    1618         </simplesect>
    1619        
    1620       </sect3>
    1621 
    1622       <sect3 id="core_ref.rules.datalayer.documentation">
    1623         <title>Documentation</title>
    1624 
    1625         <para>
    1626           The data layer code needs documentation. A simple approach is used for
    1627           Javadoc documentation
    1628         </para>
    1629        
    1630         <simplesect id="core_ref.rules.datalayer.documentation.class">
    1631           <title>Class documentation</title>
    1632           <para>
    1633             The documentation for the class doesn't have to be very lengthy. A single
    1634             sentence is usually enough. Provide tags for the author, version, last modification date
    1635             and a reference to the corresponding class in the <package>net.sf.basedb.core</package>
    1636             package.
    1637           </para>
    1638          
    1639           <programlisting language="java">
     2182            <para>
     2183              In this case, we use the <code>@hibernate.one-to-one</code> mapping
     2184              in both classes. The <code>constrained="true"</code> tag in <classname docapi="net.sf.basedb.core.data">UserData</classname>
     2185              tells Hibernate to always insert the password first, and then the user. The makes it
     2186              possible to use the (auto-generated) id for the password as the id
     2187              for the user. This is controlled by the mapping for the <methodname>UserData.getId()</methodname>
     2188              method, which uses the <code>foreign</code> id generator. This generator will look
     2189              at the password property, ie. call <methodname>getPassword().getId()</methodname>
     2190              to find the id for the user. Also note the initialisation code and <code>cascade="all"</code>
     2191              tag in the <methodname>UserData.getPassword()</methodname> method. This is needed
     2192              to avoid <classname>NullPointerException</classname>:s and to make sure everything
     2193              is created and deleted properly.
     2194            </para>
     2195
     2196            <para>
     2197              See also:
     2198            </para>
     2199           
     2200          <itemizedlist>
     2201            <listitem>
     2202              <para>
     2203              "Hibernate in action", chapter 6.3.1 "One-to-one association", page 220-225
     2204              </para>
     2205            </listitem>
     2206            <listitem>
     2207              <para>
     2208              Hibernate reference documentation: <ulink
     2209                url="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#d0e7576">5.1.7. 5.1.7. Mapping one to one and many to one associations</ulink>
     2210              </para>
     2211            </listitem>
     2212            </itemizedlist>
     2213
     2214          </listitem>
     2215        </varlistentry>
     2216
     2217        <varlistentry>
     2218          <term>Class documentation</term>
     2219          <listitem>
     2220            <para>
     2221              The documentation for the class doesn't have to be very lengthy. A single
     2222              sentence is usually enough. Provide tags for the author, version, last modification date
     2223              and a reference to the corresponding class in the <package>net.sf.basedb.core</package>
     2224              package.
     2225            </para>
     2226           
     2227            <programlisting language="java">
    16402228/**
    16412229   This class holds information about any items.
    16422230
    16432231   @author Your name
    1644    @version 2.0
     2232   @since 2.0
    16452233   @see net.sf.basedb.core.AnyItem
    16462234   @base.modified $Date: 2007-08-17 09:18:29 +0200 (Fri, 17 Aug 2007) $
     
    16532241}
    16542242</programlisting>
    1655          
    1656         </simplesect>
    1657        
    1658         <simplesect id="core_ref.rules.datalayer.documentation.method">
    1659           <title>Method documentation</title>
    1660          
    1661           <para>
    1662           Write a short one-sentence description for all public getter methods. You do not
    1663           have document the parameters or the setter methods, since it would just be a
    1664           repetition. Methods defined by interfaces are documented in the interface class.
    1665           You should not have to write any documentation for those methods.
    1666           </para>
    1667          
    1668           <para>
    1669             For the inverse end of an association, which has only package private methods,
    1670             write a notice about this and provide a link to to non-inverse end.
    1671           </para>
    1672          
    1673           <programlisting language="java">
     2243          </listitem>
     2244        </varlistentry>
     2245
     2246        <varlistentry>
     2247          <term>Method documentation</term>
     2248          <listitem>
     2249            <para>
     2250            Write a short one-sentence description for all public getter methods. You do not
     2251            have document the parameters or the setter methods, since it would just be a
     2252            repetition. Methods defined by interfaces are documented in the interface class.
     2253            You should not have to write any documentation for those methods.
     2254            </para>
     2255           
     2256            <para>
     2257              For the inverse end of an association, which has only package private methods,
     2258              write a notice about this and provide a link to to non-inverse end.
     2259            </para>
     2260           
     2261            <programlisting language="java">
     2262<![CDATA[
    16742263// UserData.java
    16752264private String address;
     
    16872276}
    16882277
    1689 private Set&lt;GroupData&gt; groups;
     2278private Set<GroupData> groups;
    16902279/**
    16912280   This is the inverse end.
     
    16962285      class="net.sf.basedb.core.data.GroupData"
    16972286*/
    1698 Set&lt;GroupData&gt; getGroups()
     2287Set<GroupData> getGroups()
    16992288{
    17002289   return groups;
    17012290}
    1702 void setGroups(Set&lt;GroupData&gt; groups)
     2291void setGroups(Set<GroupData> groups)
    17032292{
    17042293   this.groups = groups;
    17052294}
    1706 </programlisting>
    1707          
    1708         </simplesect>
    1709        
    1710         <simplesect id="core_ref.rules.datalayer.documentation.field">
    1711           <title>Field documentation</title>
    1712           <para>
    1713             Write a short one-sentence description for <code>public static final</code>
    1714             fields. Private fields does not have to be documented.
    1715           </para>
    1716          
    1717           <programlisting language="java">
     2295]]>
     2296</programlisting>
     2297          </listitem>
     2298        </varlistentry>
     2299
     2300        <varlistentry>
     2301          <term>Field documentation</term>
     2302          <listitem>
     2303            <para>
     2304              Write a short one-sentence description for <code>public static final</code>
     2305              fields. Private fields does not have to be documented.
     2306            </para>
     2307           
     2308            <programlisting language="java">
    17182309/**
    17192310   The maximum length of the name of an item that can be
     
    17212312   @see #setName(String)
    17222313*/
    1723 public static int MAX_NAME_LENGTH = 255;
    1724 </programlisting>
    1725 
    1726         </simplesect>
    1727        
    1728         <simplesect id="core_ref.rules.datalayer.documentation.uml">
    1729           <title>UML diagram</title>
    1730          
     2314public static final int MAX_NAME_LENGTH = 255;
     2315</programlisting>
     2316          </listitem>
     2317        </varlistentry>
     2318
     2319        <varlistentry>
     2320          <term>UML diagram</term>
     2321          <listitem>
    17312322          <para>
    17322323            Groups of related classes should be included in an UML-like
     
    17382329            <xref linkend="documentation.magicdraw" />.
    17392330          </para>
    1740         </simplesect>
    1741 
    1742        
    1743       </sect3>
     2331          </listitem>
     2332        </varlistentry>
     2333      </variablelist>
    17442334
    17452335    </sect2>
  • trunk/lib/docbook/custom-styles/docbook/plain/css/docbook.css

    r5244 r5673  
    156156  margin-top: 0px;
    157157}
     158.term {
     159  font-style: italic;
     160}
    158161
    159162/* ------------------------------------------------------------------- }}} */
Note: See TracChangeset for help on using the changeset viewer.