1 8 9 package persist; 10 11 import java.io.File ; 12 13 import com.sleepycat.je.DatabaseException; 14 import com.sleepycat.je.Environment; 15 import com.sleepycat.je.EnvironmentConfig; 16 import com.sleepycat.persist.EntityCursor; 17 import com.sleepycat.persist.EntityStore; 18 import com.sleepycat.persist.PrimaryIndex; 19 import com.sleepycat.persist.StoreConfig; 20 import com.sleepycat.persist.model.Entity; 21 import com.sleepycat.persist.model.KeyField; 22 import com.sleepycat.persist.model.Persistent; 23 import com.sleepycat.persist.model.PrimaryKey; 24 25 public class CustomKeyOrderExample { 26 27 @Entity 28 static class Person { 29 30 @PrimaryKey 31 ReverseOrder name; 32 33 Person(String name) { 34 this.name = new ReverseOrder(name); 35 } 36 37 private Person() {} 39 @Override  40 public String toString() { 41 return name.value; 42 } 43 } 44 45 @Persistent 46 static class ReverseOrder implements Comparable <ReverseOrder> { 47 48 @KeyField(1) 49 String value; 50 51 ReverseOrder(String value) { 52 this.value = value; 53 } 54 55 private ReverseOrder() {} 57 public int compareTo(ReverseOrder o) { 58 return o.value.compareTo(value); 59 } 60 } 61 62 public static void main(String [] args) 63 throws DatabaseException { 64 65 if (args.length != 2 || !"-h".equals(args[0])) { 66 System.err.println 67 ("Usage: java " + CustomKeyOrderExample.class.getName() + 68 " -h <envHome>"); 69 System.exit(2); 70 } 71 CustomKeyOrderExample example = 72 new CustomKeyOrderExample(new File (args[1])); 73 example.run(); 74 example.close(); 75 } 76 77 private Environment env; 78 private EntityStore store; 79 80 private CustomKeyOrderExample(File envHome) 81 throws DatabaseException { 82 83 84 EnvironmentConfig envConfig = new EnvironmentConfig(); 85 envConfig.setAllowCreate(true); 86 envConfig.setTransactional(true); 87 env = new Environment(envHome, envConfig); 88 89 90 StoreConfig storeConfig = new StoreConfig(); 91 storeConfig.setAllowCreate(true); 92 storeConfig.setTransactional(true); 93 store = new EntityStore(env, "TestStore", storeConfig); 94 } 95 96 private void run() 97 throws DatabaseException { 98 99 PrimaryIndex<ReverseOrder,Person> index = 100 store.getPrimaryIndex(ReverseOrder.class, Person.class); 101 102 index.put(new Person("Andy")); 103 index.put(new Person("Lisa")); 104 index.put(new Person("Zola")); 105 106 107 EntityCursor<Person> people = index.entities(); 108 try { 109 for (Person person : people) { 110 System.out.println(person); 111 } 112 } finally { 113 people.close(); 114 } 115 } 116 117 private void close() 118 throws DatabaseException { 119 120 store.close(); 121 env.close(); 122 } 123 } 124
| Popular Tags
|