1 package org.hibernate.id; 3 4 import java.io.Serializable ; 5 import java.sql.PreparedStatement ; 6 import java.sql.ResultSet ; 7 import java.sql.SQLException ; 8 import java.util.Properties ; 9 10 import org.apache.commons.logging.Log; 11 import org.apache.commons.logging.LogFactory; 12 import org.hibernate.HibernateException; 13 import org.hibernate.MappingException; 14 import org.hibernate.exception.JDBCExceptionHelper; 15 import org.hibernate.dialect.Dialect; 16 import org.hibernate.engine.SessionImplementor; 17 import org.hibernate.mapping.Table; 18 import org.hibernate.type.Type; 19 import org.hibernate.util.PropertiesHelper; 20 21 33 34 public class SequenceGenerator implements PersistentIdentifierGenerator, Configurable { 35 36 39 public static final String SEQUENCE = "sequence"; 40 41 45 public static final String PARAMETERS = "parameters"; 46 47 private String sequenceName; 48 private String parameters; 49 private Type identifierType; 50 private String sql; 51 52 private static final Log log = LogFactory.getLog(SequenceGenerator.class); 53 54 public void configure(Type type, Properties params, Dialect dialect) throws MappingException { 55 this.sequenceName = PropertiesHelper.getString(SEQUENCE, params, "hibernate_sequence"); 56 this.parameters = params.getProperty(PARAMETERS); 57 String schemaName = params.getProperty(SCHEMA); 58 String catalogName = params.getProperty(CATALOG); 59 60 if (sequenceName.indexOf(dialect.getSchemaSeparator() ) < 0) { 61 sequenceName = Table.qualify( catalogName, schemaName, sequenceName, dialect.getSchemaSeparator() ); 62 } 63 64 this.identifierType = type; 65 sql = dialect.getSequenceNextValString(sequenceName); 66 } 67 68 public Serializable generate(SessionImplementor session, Object obj) 69 throws HibernateException { 70 71 try { 72 73 PreparedStatement st = session.getBatcher().prepareSelectStatement(sql); 74 try { 75 ResultSet rs = st.executeQuery(); 76 final Serializable result; 77 try { 78 rs.next(); 79 result = IdentifierGeneratorFactory.get( 80 rs, identifierType 81 ); 82 } 83 finally { 84 rs.close(); 85 } 86 if ( log.isDebugEnabled() ) 87 log.debug("Sequence identifier generated: " + result); 88 return result; 89 } 90 finally { 91 session.getBatcher().closeStatement(st); 92 } 93 94 } 95 catch (SQLException sqle) { 96 throw JDBCExceptionHelper.convert( 97 session.getFactory().getSQLExceptionConverter(), 98 sqle, 99 "could not get next sequence value", 100 sql 101 ); 102 } 103 104 } 105 106 public String [] sqlCreateStrings(Dialect dialect) throws HibernateException { 107 String [] ddl = dialect.getCreateSequenceStrings(sequenceName); 108 if ( parameters!=null ) ddl[ddl.length-1] += ' ' + parameters; 109 return ddl; 110 } 111 112 public String [] sqlDropStrings(Dialect dialect) throws HibernateException { 113 return dialect.getDropSequenceStrings(sequenceName); 114 } 115 116 public Object generatorKey() { 117 return sequenceName; 118 } 119 120 } 121 | Popular Tags |