01: /*-
02: * See the file LICENSE for redistribution information.
03: *
04: * Copyright (c) 2002,2008 Oracle. All rights reserved.
05: *
06: * $Id: PersistKeyAssigner.java,v 1.11.2.5 2008/01/07 15:14:20 cwl Exp $
07: */
08:
09: package com.sleepycat.persist.impl;
10:
11: import com.sleepycat.bind.tuple.TupleBase;
12: import com.sleepycat.je.DatabaseEntry;
13: import com.sleepycat.je.DatabaseException;
14: import com.sleepycat.je.Sequence;
15:
16: /**
17: * Assigns primary keys from a Sequence.
18: *
19: * This class is used directly by PrimaryIndex, not via an interface. To avoid
20: * making a public interface, the PersistEntityBinding contains a reference to
21: * a PersistKeyAssigner, and the PrimaryIndex gets the key assigner from the
22: * binding. See the PrimaryIndex constructor for more information.
23: *
24: * @author Mark Hayes
25: */
26: public class PersistKeyAssigner {
27:
28: private Catalog catalog;
29: private Format keyFieldFormat;
30: private Format entityFormat;
31: private boolean rawAccess;
32: private Sequence sequence;
33:
34: PersistKeyAssigner(PersistKeyBinding keyBinding,
35: PersistEntityBinding entityBinding, Sequence sequence) {
36: catalog = keyBinding.catalog;
37: /* getSequenceKeyFormat will validate the field type for a sequence. */
38: keyFieldFormat = keyBinding.keyFormat.getSequenceKeyFormat();
39: entityFormat = entityBinding.entityFormat;
40: rawAccess = entityBinding.rawAccess;
41: this .sequence = sequence;
42: }
43:
44: public boolean assignPrimaryKey(Object entity, DatabaseEntry key)
45: throws DatabaseException {
46:
47: /*
48: * The keyFieldFormat is the format of a simple integer field. For a
49: * composite key class it is the contained integer field. By writing
50: * the Long sequence value using that format, the output data can then
51: * be read to construct the actual key instance, whether it is a simple
52: * or composite key class, and assign it to the primary key field in
53: * the entity object.
54: */
55: if (entityFormat.isPriKeyNullOrZero(entity, rawAccess)) {
56: Long value = sequence.get(null, 1);
57: RecordOutput output = new RecordOutput(catalog, rawAccess);
58: keyFieldFormat.writeObject(value, output, rawAccess);
59: TupleBase.outputToEntry(output, key);
60: EntityInput input = new RecordInput(catalog, rawAccess,
61: null, 0, key.getData(), key.getOffset(), key
62: .getSize());
63: entityFormat.getReader().readPriKey(entity, input,
64: rawAccess);
65: return true;
66: } else {
67: return false;
68: }
69: }
70: }
|