1 20 21 package com.methodhead.aikp; 22 23 import java.sql.ResultSet ; 24 import java.sql.SQLException ; 25 26 import java.util.List ; 27 import java.util.Map ; 28 29 import com.methodhead.persistable.ConnectionSingleton; 30 import com.methodhead.persistable.Persistable; 31 import com.methodhead.persistable.Key; 32 import com.methodhead.persistable.KeyedPersistable; 33 import com.methodhead.persistable.KeyFactory; 34 import com.methodhead.persistable.PersistableException; 35 import org.apache.commons.beanutils.DynaClass; 36 import org.apache.log4j.Logger; 37 import org.apache.commons.lang.exception.ExceptionUtils; 38 import com.methodhead.persistable.ConnectionSingleton; 39 40 52 public abstract class AutoIntKeyPersistable 53 extends 54 KeyedPersistable { 55 56 58 public AutoIntKeyPersistable( 59 DynaClass dynaClass ) { 60 61 super( dynaClass ); 62 } 63 64 66 68 private static class IntKeyFactory 69 implements 70 KeyFactory { 71 72 public Key newInstance() { 73 return new IntKey(); 74 } 75 } 76 77 79 82 protected synchronized IntKey newKey( 83 String name ) { 84 85 String sql = null; 86 87 ResultSet rs = null; 88 89 try { 90 sql = 91 "SELECT " + 92 " value " + 93 "FROM " + 94 " mh_id " + 95 "WHERE " + 96 " name=" + getSqlLiteral( name ); 97 98 rs = ConnectionSingleton.runQuery( sql ); 99 100 if ( rs == null ) { 101 throw new SQLException ( "Null result set." ); 102 } 103 104 if ( !rs.next() ) { 105 sql = 106 "INSERT INTO " + 107 " mh_id " + 108 "( " + 109 " name, " + 110 " value ) " + 111 "VALUES ( " + 112 " " + getSqlLiteral( name ) + ", " + 113 " 2" + 114 ")"; 115 116 ConnectionSingleton.runUpdate( sql ); 117 118 return new IntKey( 1 ); 119 } 120 else { 121 int value = rs.getInt( "value" ); 122 123 sql = 124 "UPDATE " + 125 " mh_id " + 126 "SET " + 127 " value=" + ( value + 1 ) + " " + 128 "WHERE " + 129 " name=" + getSqlLiteral( name ); 130 131 ConnectionSingleton.runUpdate( sql ); 132 133 return new IntKey( value ); 134 } 135 } 136 catch ( SQLException e ) { 137 String msg = "Creating new key for \"" + name + "\". " + ExceptionUtils.getStackTrace( e ); 138 logger_.error( msg ); 139 throw new RuntimeException ( msg ); 140 } 141 finally { 142 ConnectionSingleton.close( rs ); 143 } 144 } 145 146 149 public void saveNew() { 150 super.saveNew( newKey( getDynaClass().getName() ) ); 151 } 152 153 158 public void load( 159 String whereClause ) { 160 161 super.load( whereClause, new IntKeyFactory() ); 162 163 } 164 165 168 public static List loadAll( 169 DynaClass dynaClass, 170 String whereClause, 171 String orderByClause ) { 172 173 return 174 KeyedPersistable.loadAll( 175 dynaClass, 176 whereClause, 177 orderByClause, 178 new IntKeyFactory() ); 179 } 180 181 183 185 private static Logger logger_ = Logger.getLogger( AutoIntKeyPersistable.class ); 186 } 187 | Popular Tags |