1/*- 2 * See the file LICENSE for redistribution information. 3 * 4 * Copyright (c) 2002,2008 Oracle. All rights reserved. 5 * 6 * $Id: PersistKeyAssigner.java,v 1.1 2008/02/07 17:12:27 mark Exp $ 7 */ 8 9package com.sleepycat.persist.impl; 10 11import com.sleepycat.bind.tuple.TupleBase; 12import com.sleepycat.db.DatabaseEntry; 13import com.sleepycat.db.DatabaseException; 14import com.sleepycat.db.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 */ 26public 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, 36 Sequence sequence) { 37 catalog = keyBinding.catalog; 38 /* getSequenceKeyFormat will validate the field type for a sequence. */ 39 keyFieldFormat = keyBinding.keyFormat.getSequenceKeyFormat(); 40 entityFormat = entityBinding.entityFormat; 41 rawAccess = entityBinding.rawAccess; 42 this.sequence = sequence; 43 } 44 45 public boolean assignPrimaryKey(Object entity, DatabaseEntry key) 46 throws DatabaseException { 47 48 /* 49 * The keyFieldFormat is the format of a simple integer field. For a 50 * composite key class it is the contained integer field. By writing 51 * the Long sequence value using that format, the output data can then 52 * be read to construct the actual key instance, whether it is a simple 53 * or composite key class, and assign it to the primary key field in 54 * the entity object. 55 */ 56 if (entityFormat.isPriKeyNullOrZero(entity, rawAccess)) { 57 Long value = sequence.get(null, 1); 58 RecordOutput output = new RecordOutput(catalog, rawAccess); 59 keyFieldFormat.writeObject(value, output, rawAccess); 60 TupleBase.outputToEntry(output, key); 61 EntityInput input = new RecordInput 62 (catalog, rawAccess, null, 0, 63 key.getData(), key.getOffset(), key.getSize()); 64 entityFormat.getReader().readPriKey(entity, input, rawAccess); 65 return true; 66 } else { 67 return false; 68 } 69 } 70} 71