001: /**
002: * Copyright (C) 2006, 2007 David Bulmore, Software Sensation Inc.
003: * All Rights Reserved.
004: *
005: * This file is part of JPersist.
006: *
007: * JPersist is free software; you can redistribute it and/or modify it under
008: * the terms of the GNU General Public License (Version 2) as published by
009: * the Free Software Foundation.
010: *
011: * JPersist is distributed in the hope that it will be useful, but WITHOUT
012: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014: * for more details.
015: *
016: * You should have received a copy of the GNU General Public License
017: * along with JPersist; if not, write to the Free Software Foundation,
018: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
019: */package jpersist.example;
020:
021: import java.sql.Savepoint;
022: import java.util.Collection;
023: import java.util.Vector;
024: import java.util.logging.Level;
025: import jpersist.Database;
026: import jpersist.DatabaseManager;
027: import jpersist.Entity;
028: import jpersist.JPersistException;
029: import jpersist.PersistentObject;
030: import jpersist.Result;
031: import jpersist.TransactionManager;
032: import jpersist.annotations.UpdateNullValues;
033:
034: /* uncomment for DBCP (Apache Commons Connection Pooling) - Need commons-pool and commons-dbcp
035: import org.apache.commons.dbcp.ConnectionFactory;
036: import org.apache.commons.dbcp.DriverManagerConnectionFactory;
037: import org.apache.commons.dbcp.PoolableConnectionFactory;
038: import org.apache.commons.dbcp.PoolingDataSource;
039: import org.apache.commons.pool.impl.GenericObjectPool;
040: */
041:
042: public class DatabaseExample {
043: public DatabaseExample(DatabaseManager dbm) {
044: try {
045: // Clean out contacts
046: dbm.executeUpdate("delete from contacts");
047:
048: // Inserting contact with associations
049: Contact contact = new Contact("deisenhower", "mypasswd5",
050: "Dwight", "Eisenhower", "United States",
051: "deisenhower@unitedstates.gov");
052:
053: contact.getSupport().add(
054: new Support("Request", "New", "no phone",
055: "deisenhower@unitedstates.gov",
056: "Can I have my bust on a dollar, please."));
057: contact.getSupport().add(
058: new Support("Response", "Pending", "no phone",
059: "deisenhower@unitedstates.gov",
060: "Yes, but you may have to share it."));
061: contact.getSupport().add(
062: new Support("Request", "New", "no phone",
063: "deisenhower@unitedstates.gov",
064: "Share it with who?"));
065:
066: contact.getOrders().add(
067: new Order("Dwight D. Eisenhower Dollar",
068: new Integer(100), new Double(1.00),
069: "unverified"));
070: contact.getOrders().add(
071: new Order("Susan B. Anthony Dollar", new Integer(
072: 100), new Double(1.00), "unverified"));
073:
074: // Saving within an automatic transaction (covers all relationships)
075: contact.save(dbm);
076:
077: // Add an associated record and update
078: contact
079: .getSupport()
080: .add(
081: new Support("Response", "Closed",
082: "no phone",
083: "deisenhower@unitedstates.gov",
084: "You'll have to share with Susan Anthony."));
085: contact.save(dbm);
086:
087: /*
088: * Saving within a transaction manager
089: */
090: new TransactionManager(dbm) {
091: public void run() throws JPersistException {
092: // Inserting individually
093: new Contact("alincoln", "mypasswd1", "Abraham",
094: "Lincoln", null,
095: "alincoln@unitedstates.gov").save(this );
096: new Support("alincoln", "Request", "New",
097: "no phone", "alincoln@unitedstates.gov",
098: "Can I have my bust on a penny, please.")
099: .save(this );
100: new Order("alincoln", "Abraham Lincoln Penny",
101: new Integer(100), new Double(.01),
102: "unverified").save(this );
103:
104: new Contact("tjefferson", "mypasswd2", "Thomas",
105: "Jefferson", "United States",
106: "tjefferson@unitedstates.gov").save(this );
107: new Support("tjefferson", "Request", "New",
108: "no phone", "tjefferson@unitedstates.gov",
109: "Can I have my bust on a nickel, please.")
110: .save(this );
111: new Order("tjefferson", "Thomas Jefferson Nickel",
112: new Integer(100), new Double(.05),
113: "unverified").save(this );
114:
115: // Insert new contact only
116: Contact contact1 = new Contact("fdroosevelt",
117: "mypasswd3", "Franklin", "Roosevelt",
118: "United States",
119: "fdroosevelt@unitedstates.gov");
120: contact1.save(this );
121:
122: // Add associated records and update
123: contact1
124: .getSupport()
125: .add(
126: new Support(
127: "fdroosevelt",
128: "Request",
129: "New",
130: "no phone",
131: "fdroosevelt@unitedstates.gov",
132: "Can I have my bust on a dime, please."));
133: contact1.getOrders().add(
134: new Order("fdroosevelt",
135: "Franklin Delano Roosevelt Dime",
136: new Integer(100), new Double(.10),
137: "unverified"));
138: contact1.save(this );
139:
140: // can still freely use commit, savepoint and rollback
141:
142: commit();
143:
144: Savepoint savepoint = null;
145:
146: if (supportsSavepoints())
147: savepoint = setSavepoint();
148:
149: new Contact("gwashington", "mypasswd4", "George",
150: "Washington", "United States",
151: "gwashington@unitedstates.gov").save(this );
152: new Support("gwashington", "Request", "New",
153: "no phone", "gwashington@unitedstates.gov",
154: "Can I have my bust on a quarter, please.")
155: .save(this );
156: new Order("gwashington",
157: "George Washington Quarter", new Integer(
158: 100), new Double(.25), "unverified")
159: .save(this );
160:
161: if (supportsSavepoints())
162: rollback(savepoint);
163:
164: // same end result
165: getDatabase().saveObject(
166: new Contact("jkennedy", "mypasswd4",
167: "John", "Kennedy", "United States",
168: "gwashington@unitedstates.gov"));
169: getDatabase()
170: .saveObject(
171: new Support(
172: "jkennedy",
173: "Request",
174: "New",
175: "no phone",
176: "gwashington@unitedstates.gov",
177: "Can I have my bust on the half dollar, please."));
178:
179: // also same end result
180: saveObject(new Support("jkennedy", "Response",
181: "Pending", "no phone",
182: "nobody@unitedstates.gov",
183: "Yes, we'll let you know"));
184: saveObject(new Order("jkennedy",
185: "John Fitzgerald Kennedy Half Dollar",
186: new Integer(100), new Double(.50),
187: "unverified"));
188: }
189: }.executeTransaction();
190:
191: /*
192: * The jpersist.DatabaseManager way to load objects
193: */
194:
195: // Load based on information contained in classes (load associations seperately)
196: contact = dbm.loadObject(Contact.class, false,
197: "where :contactId like 'tjef%'");
198: dbm.loadAssociations(contact);
199: System.out.println("\ncontactId = "
200: + contact.getContactId());
201:
202: // or Load based on information contained in objects
203: contact = dbm.loadObject(new Contact("tjef%"));
204: System.out.println("contactId = " + contact.getContactId());
205:
206: // or with variable argument parameters
207: contact = dbm.loadObject(Contact.class,
208: "where :contactId like ?", "tjef%");
209: System.out.println("contactId = " + contact.getContactId()
210: + "\n");
211:
212: // Load a collection of objects from the database (without associations)
213: Collection<Contact> c = dbm.loadObjects(
214: new Vector<Contact>(), Contact.class, false);
215:
216: for (Contact contact2 : c)
217: System.out.println("contactId = "
218: + contact2.getContactId());
219:
220: System.out.println();
221:
222: /*
223: * The jpersist.Database way to load objects
224: */
225:
226: Database db = dbm.getDatabase();
227:
228: try {
229: // Query all
230: Result<Contact> result = db.queryObject(Contact.class,
231: "order by :lastName");
232:
233: // Result is Iterable
234: for (Contact contact3 : result) {
235: System.out.println(contact3);
236:
237: // Update a couple of mistakes
238: if (contact3.getContactId().startsWith("jkennedy")) {
239: contact3.setEmail("jkennedy@unitedstates.gov");
240:
241: for (Support support : contact3.getSupport())
242: if (support.getEmail().startsWith("gwash")
243: || support.getEmail().startsWith(
244: "nobody"))
245: support
246: .setEmail("jkennedy@unitedstates.gov");
247:
248: contact3.save(db);
249: } else if (contact3.getContactId().startsWith(
250: "fdroosevelt")) {
251: contact3.setCompanyName(null);
252:
253: db.saveObject(contact3);
254: }
255: }
256:
257: result.close();
258:
259: result = db.queryObject(Contact.class,
260: "order by :lastName");
261:
262: // Print and delete
263: while (result.hasNext()
264: && (contact = result.next()) != null) {
265: System.out.println(contact);
266: db.deleteObject(contact);
267: }
268:
269: result.close();
270: } finally {
271: // also closes any open results
272: db.close();
273: }
274: } catch (Exception e) {
275: e.printStackTrace();
276: }
277: }
278:
279: /*
280: static DataSource getDbcpDataSource() throws ClassNotFoundException
281: {
282: Class.forName("org.hsqldb.jdbcDriver");
283:
284: GenericObjectPool connectionPool = new GenericObjectPool(null);
285: ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:hsqldb:file:/hsqldb/jdbc/jpersist", null, null);
286: PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,connectionPool,null,null,false,true);
287: return new PoolingDataSource(connectionPool);
288: }
289: */
290: public static void main(String[] args) {
291: DatabaseManager dbm = null;
292:
293: try {
294: try {
295: DatabaseManager.setLogLevel(Level.OFF);
296:
297: dbm = DatabaseManager
298: .getXmlDefinedDatabaseManager("jpersist");
299: //dbm = DatabaseManager.getUrlDefinedDatabaseManager("jpersist", 10, "jpersist",
300: // "org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:/hsqldb/jdbc/jpersist");
301: //dbm = DatabaseManager.getDataSourceDatabaseManager("jpersist", 10, getDbcpDataSource(), null, null);
302:
303: for (int i = 0; i < 1; i++) {
304: new DatabaseExample(dbm);
305: System.out.println("count=" + (i + 1));
306: }
307: } finally {
308: // also closes any open jpersist.Database
309: dbm.close();
310: }
311: } catch (Exception e) {
312: e.printStackTrace();
313: }
314: }
315:
316: @UpdateNullValues
317: public static class Contact extends PersistentObject {
318: private String contactId, password, firstName, lastName,
319: companyName, email;
320: private Vector<Support> support = new Vector<Support>();
321: private Vector<Order> orders = new Vector<Order>();
322:
323: public Contact() {
324: }
325:
326: public Contact(String contactId) {
327: this .contactId = contactId;
328: }
329:
330: public Contact(String contactId, String password,
331: String firstName, String lastName, String companyName,
332: String email) {
333: this .contactId = contactId;
334: this .password = password;
335: this .firstName = firstName;
336: this .lastName = lastName;
337: this .companyName = companyName;
338: this .email = email;
339: }
340:
341: public String getContactId() {
342: return contactId;
343: }
344:
345: public void setContactId(String id) {
346: contactId = id;
347: }
348:
349: public String getPassword() {
350: return password;
351: }
352:
353: public void setPassword(String passwd) {
354: password = passwd;
355: }
356:
357: public String getFirstName() {
358: return firstName;
359: }
360:
361: public void setFirstName(String fName) {
362: firstName = fName;
363: }
364:
365: public String getLastName() {
366: return lastName;
367: }
368:
369: public void setLastName(String lName) {
370: lastName = lName;
371: }
372:
373: public String getCompanyName() {
374: return companyName;
375: }
376:
377: public void setCompanyName(String name) {
378: companyName = name;
379: }
380:
381: public String getEmail() {
382: return email;
383: }
384:
385: public void setEmail(String email) {
386: this .email = email;
387: }
388:
389: // Associations
390: public Vector<Support> getDbAssociation(Support c) {
391: return support;
392: }
393:
394: public void setDbAssociation(Support c, Vector<Support> s) {
395: support = s;
396: }
397:
398: public Vector<Order> getDbAssociation(Order c) {
399: return orders;
400: }
401:
402: public void setDbAssociation(Order c, Vector<Order> o) {
403: orders = o;
404: }
405:
406: // association convenience (is optional)
407: public Vector<Support> getSupport() {
408: return support;
409: }
410:
411: public void setSupport(Vector<Support> support) {
412: this .support = support;
413: }
414:
415: public Vector<Order> getOrders() {
416: return orders;
417: }
418:
419: public void setOrders(Vector<Order> orders) {
420: this .orders = orders;
421: }
422:
423: public String toString() {
424: String returnString = contactId + ", " + firstName + ", "
425: + lastName + ", " + companyName + ", " + email
426: + "\n";
427:
428: if (support != null)
429: for (Support s : support)
430: returnString += s + "\n";
431:
432: if (orders != null)
433: for (Order o : orders)
434: returnString += o + "\n";
435:
436: return returnString;
437: }
438: }
439:
440: public static class Order extends Entity // can optionally extend Entity for esthetics
441: {
442: private Long orderId;
443: private Integer quantity;
444: private Double price;
445: private String contactId, product, status;
446:
447: public Order() {
448: }
449:
450: public Order(String product, Integer quantity, Double price,
451: String status) {
452: this .product = product;
453: this .quantity = quantity;
454: this .price = price;
455: this .status = status;
456: }
457:
458: public Order(String contactId, String product,
459: Integer quantity, Double price, String status) {
460: this .contactId = contactId;
461: this .product = product;
462: this .quantity = quantity;
463: this .price = price;
464: this .status = status;
465: }
466:
467: public Long getOrderId() {
468: return orderId;
469: }
470:
471: public void setOrderId(Long orderId) {
472: this .orderId = orderId;
473: }
474:
475: public String getContactId() {
476: return contactId;
477: }
478:
479: public void setContactId(String contactId) {
480: this .contactId = contactId;
481: }
482:
483: public String getProduct() {
484: return product;
485: }
486:
487: public void setProduct(String product) {
488: this .product = product;
489: }
490:
491: public Integer getQuantity() {
492: return quantity;
493: }
494:
495: public void setQuantity(Integer quantity) {
496: this .quantity = quantity;
497: }
498:
499: public Double getPrice() {
500: return price;
501: }
502:
503: public void setPrice(Double price) {
504: this .price = price;
505: }
506:
507: public String getStatus() {
508: return status;
509: }
510:
511: public void setStatus(String status) {
512: this .status = status;
513: }
514:
515: public String toString() {
516: return orderId + ", " + contactId + ", " + quantity + ", "
517: + price + ", " + product + ", " + status;
518: }
519: }
520:
521: public static class Support extends PersistentObject {
522: private Long supportId;
523: private String contactId, code, status, phone, email, request;
524:
525: public Support() {
526: }
527:
528: public Support(String code, String status, String phone,
529: String email, String request) {
530: this .code = code;
531: this .status = status;
532: this .phone = phone;
533: this .email = email;
534: this .request = request;
535: }
536:
537: public Support(String contactId, String code, String status,
538: String phone, String email, String request) {
539: this .contactId = contactId;
540: this .code = code;
541: this .status = status;
542: this .phone = phone;
543: this .email = email;
544: this .request = request;
545: }
546:
547: public Long getSupportId() {
548: return supportId;
549: }
550:
551: public void setSupportId(Long id) {
552: supportId = id;
553: }
554:
555: public String getContactId() {
556: return contactId;
557: }
558:
559: public void setContactId(String id) {
560: contactId = id;
561: }
562:
563: public String getCode() {
564: return code;
565: }
566:
567: public void setCode(String code) {
568: this .code = code;
569: }
570:
571: public String getStatus() {
572: return status;
573: }
574:
575: public void setStatus(String status) {
576: this .status = status;
577: }
578:
579: public String getPhone() {
580: return phone;
581: }
582:
583: public void setPhone(String phone) {
584: this .phone = phone;
585: }
586:
587: public String getEmail() {
588: return email;
589: }
590:
591: public void setEmail(String email) {
592: this .email = email;
593: }
594:
595: public String getRequest() {
596: return request;
597: }
598:
599: public void setRequest(String request) {
600: this .request = request;
601: }
602:
603: public String toString() {
604: return supportId + ", " + contactId + ", " + code + ","
605: + status + ", " + phone + ", " + email + ", "
606: + request;
607: }
608: }
609: }
|