1 28 29 package com.caucho.amber.idgen; 30 31 import com.caucho.amber.manager.AmberConnection; 32 import com.caucho.amber.manager.AmberPersistenceUnit; 33 import com.caucho.config.ConfigException; 34 import com.caucho.jdbc.JdbcMetaData; 35 import com.caucho.util.L10N; 36 import com.caucho.util.Log; 37 38 import javax.sql.DataSource ; 39 import java.sql.Connection ; 40 import java.sql.PreparedStatement ; 41 import java.sql.ResultSet ; 42 import java.sql.SQLException ; 43 import java.sql.Statement ; 44 import java.util.logging.Level ; 45 import java.util.logging.Logger ; 46 47 50 public class SequenceIdGenerator extends IdGenerator { 51 private static final L10N L = new L10N(SequenceIdGenerator.class); 52 private static final Logger log = Log.open(SequenceIdGenerator.class); 53 54 private AmberPersistenceUnit _manager; 55 private String _name; 56 private int _size; 57 58 private String _selectSQL; 59 60 private boolean _isInit; 61 62 65 public SequenceIdGenerator(AmberPersistenceUnit manager, 66 String name, 67 int size) 68 throws ConfigException 69 { 70 _manager = manager; 71 _name = name; 72 _size = size; 73 } 74 75 78 public long allocateGroup(AmberConnection aConn) 79 throws SQLException 80 { 81 Connection conn = aConn.getConnection(); 83 84 PreparedStatement selectStmt = conn.prepareStatement(_selectSQL); 85 86 long value = -1; 87 88 ResultSet rs = selectStmt.executeQuery(); 89 if (rs.next()) 90 value = rs.getLong(1); 91 92 rs.close(); 93 94 return value; 95 } 96 97 100 public void init(AmberPersistenceUnit amberPersistenceUnit) 101 throws SQLException 102 { 103 if (_isInit) 104 return; 105 _isInit = true; 106 107 DataSource ds = amberPersistenceUnit.getDataSource(); 108 Connection conn = ds.getConnection(); 109 try { 110 JdbcMetaData metaData = amberPersistenceUnit.getMetaData(); 111 112 _selectSQL = metaData.selectSequenceSQL(_name); 113 114 if (amberPersistenceUnit.getCreateDatabaseTables()) { 115 String sql = metaData.createSequenceSQL(_name, getGroupSize()); 116 117 try { 118 Statement stmt = conn.createStatement(); 119 stmt.executeUpdate(sql); 120 stmt.close(); 121 } catch (Exception e) { 122 log.log(Level.FINER, e.toString(), e); 123 } 124 } 125 } finally { 126 conn.close(); 127 } 128 } 129 } 130 | Popular Tags |