1 package com.jbidwatcher.auction; 2 3 4 import com.jbidwatcher.util.db.Table; 5 import com.jbidwatcher.util.db.ActiveRecord; 6 7 import java.util.List; 8 import java.util.ArrayList; 9 10 /** 11 * Category DB accessor. 12 * 13 * User: Morgan 14 * Date: Oct 21, 2007 15 * Time: 12:47:22 PM 16 * To change this template use File | Settings | File Templates. 17 */ 18 public class Category extends ActiveRecord 19 { Category()20 public Category() { 21 } 22 Category(String name)23 public Category(String name) { 24 setString("name", name); 25 } 26 findFirstByName(String name)27 public static Category findFirstByName(String name) { 28 return findFirstBy("name", name); 29 } 30 findOrCreateByName(String name)31 public static Category findOrCreateByName(String name) { 32 Category c = findFirstByName(name); 33 if (c == null) { 34 c = create(name); 35 } 36 37 return c; 38 } 39 create(String newCategory)40 public static Category create(String newCategory) { 41 Category c = new Category(newCategory); 42 String id = c.saveDB(); 43 if(id != null) c.setInteger("id", Integer.parseInt(id)); 44 return c; 45 } 46 getName()47 public String getName() { return getString("name"); } 48 getTableName()49 protected static String getTableName() { return "categories"; } 50 51 private static ThreadLocal<Table> tDB = new ThreadLocal<Table>() { 52 protected synchronized Table initialValue() { 53 return openDB(getTableName()); 54 } 55 }; 56 getRealDatabase()57 public static Table getRealDatabase() { 58 return tDB.get(); 59 } 60 getDatabase()61 protected Table getDatabase() { 62 return getRealDatabase(); 63 } 64 findFirstBy(String key, String value)65 public static Category findFirstBy(String key, String value) { 66 return (Category) findFirstBy(Category.class, key, value); 67 } 68 all()69 public static List<Category> all() { 70 return (List<Category>) findAllBySQL(Category.class, "SELECT * FROM " + getTableName()); 71 } 72 categories()73 public static List<String> categories() { 74 List<Category> categories = (List<Category>) findAllBySQL(Category.class, "SELECT name FROM " + getTableName()); 75 if(categories.isEmpty()) return null; 76 77 List<String> results = new ArrayList<String>(categories.size()); 78 79 for(Category category : categories) { 80 results.add(category.getName()); 81 } 82 83 return results; 84 } 85 } 86