KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > id > TableHiLoGenerator


1 //$Id: TableHiLoGenerator.java,v 1.8 2005/03/30 17:12:53 epbernard Exp $
2
package org.hibernate.id;
3
4 import java.io.Serializable JavaDoc;
5 import java.util.Properties JavaDoc;
6
7 import org.apache.commons.logging.Log;
8 import org.apache.commons.logging.LogFactory;
9 import org.hibernate.HibernateException;
10 import org.hibernate.dialect.Dialect;
11 import org.hibernate.engine.SessionImplementor;
12 import org.hibernate.type.Type;
13 import org.hibernate.util.PropertiesHelper;
14
15 /**
16  * <b>hilo</b><br>
17  * <br>
18  * An <tt>IdentifierGenerator</tt> that returns a <tt>Long</tt>, constructed using
19  * a hi/lo algorithm. The hi value MUST be fetched in a seperate transaction
20  * to the <tt>Session</tt> transaction so the generator must be able to obtain
21  * a new connection and commit it. Hence this implementation may not
22  * be used when the user is supplying connections. In this
23  * case a <tt>SequenceHiLoGenerator</tt> would be a better choice (where
24  * supported).<br>
25  * <br>
26  * Mapping parameters supported: table, column, max_lo
27  *
28  * @see SequenceHiLoGenerator
29  * @author Gavin King
30  */

31
32 public class TableHiLoGenerator extends TableGenerator {
33
34     /**
35      * The max_lo parameter
36      */

37     public static final String JavaDoc MAX_LO = "max_lo";
38
39     private long hi;
40     private int lo;
41     private int maxLo;
42     private Class JavaDoc returnClass;
43
44     private static final Log log = LogFactory.getLog(TableHiLoGenerator.class);
45
46     public void configure(Type type, Properties JavaDoc params, Dialect d) {
47         super.configure(type, params, d);
48         maxLo = PropertiesHelper.getInt(MAX_LO, params, Short.MAX_VALUE);
49         lo = maxLo + 1; // so we "clock over" on the first invocation
50
returnClass = type.getReturnedClass();
51     }
52
53     public synchronized Serializable JavaDoc generate(SessionImplementor session, Object JavaDoc obj)
54     throws HibernateException {
55         if (maxLo < 2) {
56             //keep the behavior consistent even for boundary usages
57
int val = ( (Integer JavaDoc) super.generate(session, obj) ).intValue();
58             return IdentifierGeneratorFactory.createNumber( val, returnClass );
59         }
60         if (lo>maxLo) {
61             int hival = ( (Integer JavaDoc) super.generate(session, obj) ).intValue();
62             lo = (hival == 0) ? 1 : 0;
63             hi = hival * (maxLo+1);
64             log.debug("new hi value: " + hival);
65         }
66
67         return IdentifierGeneratorFactory.createNumber( hi + lo++, returnClass );
68
69     }
70
71 }
72
Popular Tags