KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > persist > PersonExample


1 /*-
2  * See the file LICENSE for redistribution information.
3  *
4  * Copyright (c) 2002,2006 Oracle. All rights reserved.
5  *
6  * $Id: PersonExample.java,v 1.9 2006/10/30 21:14:05 bostic Exp $
7  */

8
9 package persist;
10
11 import java.io.File JavaDoc;
12 import java.util.HashSet JavaDoc;
13 import java.util.Set JavaDoc;
14
15 import com.sleepycat.je.DatabaseException;
16 import com.sleepycat.je.Environment;
17 import com.sleepycat.je.EnvironmentConfig;
18 import com.sleepycat.persist.EntityCursor;
19 import com.sleepycat.persist.EntityIndex;
20 import com.sleepycat.persist.EntityStore;
21 import com.sleepycat.persist.PrimaryIndex;
22 import com.sleepycat.persist.SecondaryIndex;
23 import com.sleepycat.persist.StoreConfig;
24 import com.sleepycat.persist.model.Entity;
25 import com.sleepycat.persist.model.Persistent;
26 import com.sleepycat.persist.model.PrimaryKey;
27 import com.sleepycat.persist.model.SecondaryKey;
28 import static com.sleepycat.persist.model.DeleteAction.NULLIFY;
29 import static com.sleepycat.persist.model.Relationship.ONE_TO_ONE;
30 import static com.sleepycat.persist.model.Relationship.ONE_TO_MANY;
31 import static com.sleepycat.persist.model.Relationship.MANY_TO_ONE;
32 import static com.sleepycat.persist.model.Relationship.MANY_TO_MANY;
33
34 public class PersonExample {
35
36     /* An entity class. */
37     @Entity
38     static class Person {
39
40         @PrimaryKey
41         String JavaDoc ssn;
42
43         String JavaDoc name;
44         Address address;
45
46         @SecondaryKey(relate=MANY_TO_ONE, relatedEntity=Person.class)
47         String JavaDoc parentSsn;
48
49         @SecondaryKey(relate=ONE_TO_MANY)
50         Set JavaDoc<String JavaDoc> emailAddresses = new HashSet JavaDoc<String JavaDoc>();
51
52         @SecondaryKey(relate=MANY_TO_MANY,
53                       relatedEntity=Employer.class,
54                       onRelatedEntityDelete=NULLIFY)
55         Set JavaDoc<Long JavaDoc> employerIds = new HashSet JavaDoc<Long JavaDoc>();
56
57         Person(String JavaDoc name, String JavaDoc ssn, String JavaDoc parentSsn) {
58             this.name = name;
59             this.ssn = ssn;
60             this.parentSsn = parentSsn;
61         }
62
63         private Person() {} // For deserialization
64
}
65
66     /* Another entity class. */
67     @Entity
68     static class Employer {
69
70         @PrimaryKey(sequence="ID")
71         long id;
72
73         @SecondaryKey(relate=ONE_TO_ONE)
74         String JavaDoc name;
75
76         Address address;
77
78         Employer(String JavaDoc name) {
79             this.name = name;
80         }
81
82         private Employer() {} // For deserialization
83
}
84
85     /* A persistent class used in other classes. */
86     @Persistent
87     static class Address {
88         String JavaDoc street;
89         String JavaDoc city;
90         String JavaDoc state;
91         int zipCode;
92         private Address() {} // For deserialization
93
}
94
95     /* The data accessor class for the entity model. */
96     static class PersonAccessor {
97
98         /* Person accessors */
99         PrimaryIndex<String JavaDoc,Person> personBySsn;
100         SecondaryIndex<String JavaDoc,String JavaDoc,Person> personByParentSsn;
101         SecondaryIndex<String JavaDoc,String JavaDoc,Person> personByEmailAddresses;
102         SecondaryIndex<Long JavaDoc,String JavaDoc,Person> personByEmployerIds;
103
104         /* Employer accessors */
105         PrimaryIndex<Long JavaDoc,Employer> employerById;
106         SecondaryIndex<String JavaDoc,Long JavaDoc,Employer> employerByName;
107
108         /* Opens all primary and secondary indices. */
109         public PersonAccessor(EntityStore store)
110             throws DatabaseException {
111
112             personBySsn = store.getPrimaryIndex(
113                 String JavaDoc.class, Person.class);
114
115             personByParentSsn = store.getSecondaryIndex(
116                 personBySsn, String JavaDoc.class, "parentSsn");
117
118             personByEmailAddresses = store.getSecondaryIndex(
119                 personBySsn, String JavaDoc.class, "emailAddresses");
120
121             personByEmployerIds = store.getSecondaryIndex(
122                 personBySsn, Long JavaDoc.class, "employerIds");
123
124             employerById = store.getPrimaryIndex(
125                 Long JavaDoc.class, Employer.class);
126
127             employerByName = store.getSecondaryIndex(
128                 employerById, String JavaDoc.class, "name");
129         }
130     }
131
132     public static void main(String JavaDoc[] args)
133         throws DatabaseException {
134
135         if (args.length != 2 || !"-h".equals(args[0])) {
136             System.err.println
137                 ("Usage: java " + PersonExample.class.getName() +
138                  " -h <envHome>");
139             System.exit(2);
140         }
141         PersonExample example = new PersonExample(new File JavaDoc(args[1]));
142         example.run();
143         example.close();
144     }
145
146     private Environment env;
147     private EntityStore store;
148     private PersonAccessor dao;
149
150     private PersonExample(File JavaDoc envHome)
151         throws DatabaseException {
152
153         /* Open a transactional Berkeley DB engine environment. */
154         EnvironmentConfig envConfig = new EnvironmentConfig();
155         envConfig.setAllowCreate(true);
156         envConfig.setTransactional(true);
157         env = new Environment(envHome, envConfig);
158
159         /* Open a transactional entity store. */
160         StoreConfig storeConfig = new StoreConfig();
161         storeConfig.setAllowCreate(true);
162         storeConfig.setTransactional(true);
163         store = new EntityStore(env, "PersonStore", storeConfig);
164
165         /* Initialize the data access object. */
166         dao = new PersonAccessor(store);
167     }
168
169     private void run()
170         throws DatabaseException {
171
172         /*
173          * Add a parent and two children using the Person primary index.
174          * Specifying a non-null parentSsn adds the child Person to the
175          * sub-index of children for that parent key.
176          */

177         dao.personBySsn.put
178             (new Person("Bob Smith", "111-11-1111", null));
179         dao.personBySsn.put
180             (new Person("Mary Smith", "333-33-3333", "111-11-1111"));
181         dao.personBySsn.put
182             (new Person("Jack Smith", "222-22-2222", "111-11-1111"));
183
184         /* Print the children of a parent using a sub-index and a cursor. */
185         EntityCursor<Person> children =
186             dao.personByParentSsn.subIndex("111-11-1111").entities();
187         try {
188             for (Person child : children) {
189                 System.out.println(child.ssn + ' ' + child.name);
190             }
191         } finally {
192             children.close();
193         }
194
195         /* Get Bob by primary key using the primary index. */
196         Person bob = dao.personBySsn.get("111-11-1111");
197         assert bob != null;
198
199         /*
200          * Create two employers if they do not already exist. Their primary
201          * keys are assigned from a sequence.
202          */

203         Employer gizmoInc = dao.employerByName.get("Gizmo Inc");
204         if (gizmoInc == null) {
205             gizmoInc = new Employer("Gizmo Inc");
206             dao.employerById.put(gizmoInc);
207         }
208         Employer gadgetInc = dao.employerByName.get("Gadget Inc");
209         if (gadgetInc == null) {
210             gadgetInc = new Employer("Gadget Inc");
211             dao.employerById.put(gadgetInc);
212         }
213
214         /* Bob has two jobs and two email addresses. */
215         bob.employerIds.add(gizmoInc.id);
216         bob.employerIds.add(gadgetInc.id);
217         bob.emailAddresses.add("bob@bob.com");
218         bob.emailAddresses.add("bob@gmail.com");
219
220         /* Update Bob's record. */
221         dao.personBySsn.put(bob);
222
223         /* Bob can now be found by both email addresses. */
224         bob = dao.personByEmailAddresses.get("bob@bob.com");
225         assert bob != null;
226         bob = dao.personByEmailAddresses.get("bob@gmail.com");
227         assert bob != null;
228
229         /* Bob can also be found as an employee of both employers. */
230         EntityIndex<String JavaDoc,Person> employees;
231         employees = dao.personByEmployerIds.subIndex(gizmoInc.id);
232         assert employees.contains("111-11-1111");
233         employees = dao.personByEmployerIds.subIndex(gadgetInc.id);
234         assert employees.contains("111-11-1111");
235
236         /*
237          * When an employer is deleted, the onRelatedEntityDelete=NULLIFY for
238          * the employerIds key causes the deleted ID to be removed from Bob's
239          * employerIds.
240          */

241         dao.employerById.delete(gizmoInc.id);
242         bob = dao.personBySsn.get("111-11-1111");
243         assert bob != null;
244         assert !bob.employerIds.contains(gizmoInc.id);
245     }
246
247     private void close()
248         throws DatabaseException {
249
250         store.close();
251         env.close();
252     }
253 }
254
Popular Tags