|
From: <one...@us...> - 2003-01-26 01:34:09
|
Update of /cvsroot/hibernate/Hibernate2/src/net/sf/hibernate/cfg
In directory sc8-pr-cvs1:/tmp/cvs-serv14128/sf/hibernate/cfg
Modified Files:
Configuration.java
Added Files:
Environment.java
Removed Files:
Datastore.java
Log Message:
redesigned configuration API
--- NEW FILE: Environment.java ---
//$Id: Environment.java,v 1.1 2003/01/26 01:33:34 oneovthafew Exp $
package net.sf.hibernate.cfg;
import java.io.InputStream;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.sf.hibernate.util.PropertiesHelper;
/**
* Provides access to configuration info passed in <tt>Properties</tt> objects.<br>
* <br>
* Hibernate has two property scopes:
* <ul>
* <li><b>Factory-level</b> properties may be passed to the <tt>SessionFactory</tt> when it
* instantiated. Each instance might have different property values. If no
* properties are specified, the factory calls <tt>Environment.getProperties()</tt>.
* <li><b>System-level</b> properties are shared by all factory instances and are always
* determined by the <tt>Environment</tt> properties.
* </ul>
* The only system-level property is
* <ul>
* <li><tt>hibernate.jdbc.use_streams_for_binary</tt>
* </ul>
* <tt>Environment</tt> properties are populated by calling <tt>System.getProperties()</tt>
* and then from a resource named <tt>/hibernate.properties</tt> if it exists. System
* properties override properties specified in <tt>hibernate.properties</tt>.
*
* @see SessionFactory
*/
public final class Environment {
private static final String VERSION = "2.0 beta 1";
/**
* <tt>ConnectionProvider</tt> implementor to use when obtaining connections
*/
public static final String CONNECTION_PROVIDER ="hibernate.connection.provider_class";
/**
* JDBC driver class
*/
public static final String DRIVER ="hibernate.connection.driver_class";
/**
* JDBC transaction isolation level
*/
public static final String ISOLATION ="hibernate.connection.isolation";
/**
* JDBC URL
*/
public static final String URL ="hibernate.connection.url";
/**
* JDBC user
*/
public static final String USER ="hibernate.connection.username";
/**
* JDBC password
*/
public static final String PASS ="hibernate.connection.password";
/**
* Maximum number of inactive connections for Hibernate's connection pool
*/
public static final String POOL_SIZE ="hibernate.connection.pool_size";
/**
* <tt>java.sql.Datasource</tt> JNDI name
*/
public static final String DATASOURCE ="hibernate.connection.datasource";
/**
* prefix for arbitrary JDBC connection properties
*/
public static final String CONNECTION_PREFIX = "hibernate.connection";
/**
* Maximum size for Hibernate's statement cache
*/
public static final String STATEMENT_CACHE_SIZE ="hibernate.statement_cache.size";
/**
* JNDI initial context class, <tt>Context.INITIAL_CONTEXT_FACTORY</tt>
*/
public static final String JNDI_CLASS ="hibernate.jndi.class";
/**
* JNDI provider URL, <tt>Context.PROVIDER_URL</tt>
*/
public static final String JNDI_URL ="hibernate.jndi.url";
/**
* prefix for arbitrary JNDI <tt>InitialContext</tt> properties
*/
public static final String JNDI_PREFIX = "hibernate.jndi";
/**
* JNDI name to bind to <tt>SessionFactory</tt>
*/
public static final String SESSION_FACTORY_NAME = "hibernate.session_factory_name";
/**
* Hibernate SQL <tt>Dialect</tt> class
*/
public static final String DIALECT ="hibernate.dialect";
/**
* A default database schema (owner) name to use for unqualified tablenames
*/
public static final String DEFAULT_SCHEMA = "hibernate.default_schema";
/**
* Enable logging of generated SQL to the console
*/
public static final String SHOW_SQL ="hibernate.show_sql";
/**
* Enable deep fetching using outerjoins
*/
public static final String OUTER_JOIN ="hibernate.use_outer_join";
/**
* Use <tt>java.io</tt> streams to read / write binary data from / to JDBC
*/
public static final String USE_STREAMS_FOR_BINARY = "hibernate.jdbc.use_streams_for_binary";
/**
* Use JDBC scrollable <tt>ResultSet</tt>s. This property is only necessary when there is
* no <tt>ConnectionProvider</tt>, ie. the user is supplying JDBC connections.
*/
public static final String USE_SCROLLABLE_RESULTSET = "hibernate.jdbc.use_scrollable_resultset";
/**
* Gives the JDBC driver a hint as to the number of rows that should be fetched from the database
* when more rows are needed. If <tt>0</tt>, JDBC driver default settings will be used.
*/
public static final String STATEMENT_FETCH_SIZE = "hibernate.jdbc.fetch_size";
/**
* Maximum JDBC batch size. A nonzero value enables batch updates.
*/
public static final String STATEMENT_BATCH_SIZE = "hibernate.jdbc.batch_size";
/**
* An XSLT resource used to generate "custom" XML
*/
public static final String OUTPUT_STYLESHEET ="hibernate.xml.output_stylesheet";
/**
* Maximum size of C3P0 connection pool
*/
public static final String C3P0_MAX_SIZE = "hibernate.c3p0.max_size";
/**
* Minimum size of C3P0 connection pool
*/
public static final String C3P0_MIN_SIZE = "hibernate.c3p0.min_size";
/**
* Maximum idle time for C3P0 connection pool
*/
public static final String C3P0_TIMEOUT = "hibernate.c3p0.timeout";
/**
* Maximum size of C3P0 statement cache
*/
public static final String C3P0_MAX_STATEMENTS = "hibernate.c3p0.max_statements";
/**
* Should we validate the connection on checkout? (optional)
*/
public static final String C3P0_VALIDATE_CONNECTION = "hibernate.c3p0.validate";
/**
* Maximum number of checked out connections for DBCP connection pool
*/
public static final String DBCP_MAXACTIVE = "hibernate.dbcp.maxActive";
/**
* Maximum number of idle connections for DBCP connection pool
*/
public static final String DBCP_MAXIDLE = "hibernate.dbcp.maxIdle";
/**
* Maximum idle time for connections in DBCP connection pool (ms)
*/
public static final String DBCP_MAXWAIT = "hibernate.dbcp.maxWait";
/**
* Action to take in case of an exhausted DBCP connection pool ( 0 = fail, 1 = block, 2= grow)
*/
public static final String DBCP_WHENEXHAUSTED = "hibernate.dbcp.whenExhaustedAction";
/**
* Query to execute for connection validation (optional)
*/
public static final String DBCP_VALIDATION_QUERY = "hibernate.dbcp.validationQuery";
/**
* Maximum number of checked out statements for DBCP
*/
public static final String DBCP_PS_MAXACTIVE = "hibernate.dbcp.ps.maxActive";
/**
* Maximum number of idle statements for DBCP
*/
public static final String DBCP_PS_MAXIDLE = "hibernate.dbcp.ps.maxIdle";
/**
* Maximum idle time for statements in DBCP (ms)
*/
public static final String DBCP_PS_MAXWAIT = "hibernate.dbcp.ps.maxWait";
/**
* Action to take in case of an exhausted DBCP statement pool ( 0 = fail, 1 = block, 2= grow)
*/
public static final String DBCP_PS_WHENEXHAUSTED = "hibernate.dbcp.ps.whenExhaustedAction";
/**
* <tt>TransactionFactory</tt> implementor to use for creating <tt>Transaction</tt>s
*/
public static final String TRANSACTION_STRATEGY = "hibernate.transaction.factory_class";
/**
* <tt>TransactionManagerLookup</tt> implementor to use for obtaining the <tt>TransactionManager</tt>
*/
public static final String TRANSACTION_MANAGER_STRATEGY = "hibernate.transaction.manager_lookup_class";
/**
* JNDI name of JTA <tt>UserTransaction</tt> object
*/
public static final String USER_TRANSACTION = "jta.UserTransaction";
/**
* A comma-seperated list of token substitutions to use when translating a Hibernate
* query to SQL
*/
public static final String QUERY_SUBSTITUTIONS = "hibernate.query.substitutions";
/**
* A comma-seperated list of packages that need not be specified in a query
*/
public static final String QUERY_IMPORTS = "hibernate.query.imports";
//Obsolete properties:
private static final String OUTPUT_STYLESHEET_OLD ="hibernate.output_stylesheet";
private static final String CONNECTION_PROVIDER_OLD ="hibernate.connection_provider";
private static final String DRIVER_OLD ="hibernate.driver";
private static final String ISOLATION_OLD ="hibernate.isolation";
private static final String USER_OLD ="hibernate.username";
private static final String PASS_OLD ="hibernate.password";
private static final String POOL_SIZE_OLD ="hibernate.pool_size";
private static final String STATEMENT_CACHE_SIZE_OLD ="hibernate.statement_cache_size";
private static final String DATASOURCE_OLD ="hibernate.datasource";
private static final String TRANSACTION_STRATEGY_OLD = "hibernate.transaction_factory";
private static final String URL_OLD ="hibernate.url";
private static final String USE_STREAMS_FOR_BINARY_OLD = "hibernate.use_streams_for_binary";
private static final String STATEMENT_FETCH_SIZE_OLD = "hibernate.statement.fetch_size";
private static final String USE_SCROLLABLE_RESULTSET_OLD = "hibernate.use_scrollable_resultset";
/**
* Use JDBC2 batch updates
* @deprecated
*/
public static final String USE_JDBC_BATCH = "hibernate.use_jdbc_batch";
private static final boolean jvmSupportsProxies;
private static final boolean useStreamsForBinary;
private static final boolean jvmSupportsLinkedHashCollections;
private static final Properties properties;
private static final HashMap isolationLevels = new HashMap();
private static final Map obsoleteProperties = new HashMap();
private static final Log log = LogFactory.getLog(Environment.class);
/**
* Issues warnings to the user when any obsolete property names are used.
*/
public static void verifyProperties(Properties props) {
Iterator iter = props.keySet().iterator();
while ( iter.hasNext() ) {
Object oldProp = iter.next();
Object newProp = obsoleteProperties.get(oldProp);
if ( newProp!=null ) log.warn("Usage of obsolete property: " + oldProp + " no longer supported, use: " + newProp);
}
}
static {
log.info("Hibernate " + VERSION);
isolationLevels.put( new Integer(Connection.TRANSACTION_NONE), "NONE" );
isolationLevels.put( new Integer(Connection.TRANSACTION_READ_UNCOMMITTED), "READ_UNCOMMITTED" );
isolationLevels.put( new Integer(Connection.TRANSACTION_READ_COMMITTED), "READ_COMMITTED" );
isolationLevels.put( new Integer(Connection.TRANSACTION_REPEATABLE_READ), "REPEATABLE_READ" );
isolationLevels.put( new Integer(Connection.TRANSACTION_SERIALIZABLE), "SERIALIZABLE" );
obsoleteProperties.put(CONNECTION_PROVIDER_OLD, CONNECTION_PROVIDER);
obsoleteProperties.put(DRIVER_OLD, DRIVER);
obsoleteProperties.put(ISOLATION_OLD, ISOLATION);
obsoleteProperties.put(URL_OLD, URL);
obsoleteProperties.put(PASS_OLD, PASS);
obsoleteProperties.put(USER_OLD, USER);
obsoleteProperties.put(POOL_SIZE_OLD, POOL_SIZE);
obsoleteProperties.put(STATEMENT_CACHE_SIZE_OLD, STATEMENT_CACHE_SIZE);
obsoleteProperties.put(DATASOURCE_OLD, DATASOURCE);
obsoleteProperties.put(TRANSACTION_STRATEGY_OLD, TRANSACTION_STRATEGY);
obsoleteProperties.put(OUTPUT_STYLESHEET_OLD, OUTPUT_STYLESHEET);
obsoleteProperties.put(USE_JDBC_BATCH, STATEMENT_BATCH_SIZE);
obsoleteProperties.put(USE_SCROLLABLE_RESULTSET_OLD, USE_SCROLLABLE_RESULTSET);
obsoleteProperties.put(USE_STREAMS_FOR_BINARY_OLD, USE_STREAMS_FOR_BINARY);
obsoleteProperties.put(STATEMENT_FETCH_SIZE_OLD, STATEMENT_FETCH_SIZE);
properties = new Properties();
InputStream stream = Environment.class.getResourceAsStream("/hibernate.properties");
if ( stream==null ) {
log.info("hibernate.properties not found");
}
else {
try {
properties.load(stream);
log.info("loaded properties from resource hibernate.properties");
}
catch (Exception e) {
log.error("problem loading properties from hibernate.properties");
}
}
properties.putAll( System.getProperties() );
verifyProperties(properties);
useStreamsForBinary = PropertiesHelper.getBoolean(USE_STREAMS_FOR_BINARY, properties);
if (useStreamsForBinary) log.info("using java.io streams to persist binary types");
boolean proxySupport;
try {
Class.forName("java.lang.reflect.Proxy");
proxySupport = true;
}
catch (ClassNotFoundException cnfe) {
proxySupport = false;
}
log.info("JVM proxy support: " + proxySupport);
jvmSupportsProxies = proxySupport;
boolean linkedHashSupport;
try {
Class.forName("java.util.LinkedHashSet");
linkedHashSupport = true;
}
catch (ClassNotFoundException cnfe) {
linkedHashSupport = false;
}
jvmSupportsLinkedHashCollections = linkedHashSupport;
}
/**
* Does this JVM support dynamic proxies? (Now return true because CGLIB
* proxies work on all supported JDK)
*/
public static boolean jvmSupportsProxies() {
return true;//jvmSupportsProxies;
}
/**
* Does this JVM support <tt>LinkedHashSet</tt>, <tt>LinkedHashMap</tt>?
* @see java.util.LinkedHashSet
* @see java.util.LinkedHashMap
*/
public static boolean jvmSupportsLinkedHashCollections() {
return jvmSupportsLinkedHashCollections;
}
/**
* Should we use streams to bind binary types to JDBC IN parameters?
* Property <tt>hibernate.jdbc.use_streams_for_binary</tt>.
*/
public static boolean useStreamsForBinary() {
return useStreamsForBinary;
}
private Environment() { throw new UnsupportedOperationException(); }
/**
* Return <tt>System</tt> properties, extended by any properties specified
* in <tt>hibernate.properties</tt>.
* @return Properties
*/
public static Properties getProperties() {
Properties copy = new Properties();
copy.putAll(properties);
return copy;
}
/**
* Get the name of a JDBC transaction isolation level
*
* @see java.sql.Connection
* @param isolation as defined by <tt>java.sql.Connection</tt>
* @return String
*/
public static String isolationLevelToString(int isolation) {
return (String) isolationLevels.get( new Integer(isolation) );
}
}
Index: Configuration.java
===================================================================
RCS file: /cvsroot/hibernate/Hibernate2/src/net/sf/hibernate/cfg/Configuration.java,v
retrieving revision 1.3
retrieving revision 1.4
diff -C2 -d -r1.3 -r1.4
*** Configuration.java 5 Jan 2003 02:11:20 -0000 1.3
--- Configuration.java 26 Jan 2003 01:33:34 -0000 1.4
***************
*** 2,93 ****
package net.sf.hibernate.cfg;
import java.io.InputStream;
! import java.util.*;
! import net.sf.hibernate.*;
! import net.sf.hibernate.util.XMLHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
! import org.w3c.dom.*;
! import org.xml.sax.*;
/**
! * Parses an XML configuration file like
! *
! * <pre>
! * <?xml version='1.0' encoding='utf-8'?>
! * <!DOCTYPE hibernate-configuration PUBLIC
! * "-//Hibernate/Hibernate Configuration DTD//EN"
! * "http://hibernate.sourceforge.net/hibernate-configuration.dtd">
! *
! * <hibernate-configuration>
! *
! * <property name="show_sql">false</property>
! * <property name="use_outer_join">true</property>
! * <property name="jta.UserTransaction">java:comp/UserTransaction/</property>
! *
! * <session-factory name="/jndi/name">
! * <property name="connection.datasource">my/first/datasource</property>
! * <property name="dialect">net.sf.hibernate.sql.MySQLDialect</property>
! * <mapping resource="eg/Foo.hbm.xml"/>
! * <mapping resource="eg/Bar.hbm.xml"/>
! * </session-factory>
! *
! * <session-factory name="/another/jndi/name">
! * <property name="connection.datasource">my/other/datasource</property>
! * <property name="dialect">net.sf.hibernate.sql.OracleDialect</property>
! * <mapping file="C:/mapping/my_mappings.hbm.xml"/>
! * <mapping jar="deployed.jar"/>
! * </session-factory>
! *
! * </hibernate-configuration>
! * </pre>
! *
! * and builds one or more <tt>SessionFactory</tt> instances. The top-level <tt><property>
! * </tt> declarations apply to all instances. Elements nested inside the <tt><session-factory>
! * </tt> tag apply only to that particular instance. The "<tt>hibernate.</tt>" prefix may be
! * omitted from property names. The <tt>name</tt> attribute of <tt><session-factory></tt>
! * is equivalent to the property <tt>hibernate.session_factory_name</tt>.<br>
! * <br>
! * Typical usage is for J2EE applications to place <tt>hibernate.cfg.xml</tt> in the
! * classpath and call <tt>Hibernate.configure()</tt>.
! *
! * @see Hibernate#configure()
*/
! public class Configuration {
! private Log log = LogFactory.getLog(Configuration.class);
! private String resource;
! /**
! * For use by subclasses which override <tt>getConfigurationInputStream()</tt>
! */
! protected Configuration() {
}
! public Configuration(String resource) {
! this.resource = resource;
}
! /**
! * Get the configuration file as an <tt>InputStream</tt>. Might be overridden
! * by subclasses to allow the configuration to be located by some arbitrary
! * mechanism.
! */
! protected InputStream getConfigurationInputStream() throws HibernateException {
! log.info("Configuration resource: " + resource);
! InputStream stream = Environment.class.getResourceAsStream(resource);
! if (stream==null) {
! log.warn(resource + " not found");
! throw new HibernateException(resource + " not found");
}
- return stream;
}
! private void addProperties(Node parent, Properties properties) {
NodeList children = parent.getChildNodes();
for ( int i=0; i<children.getLength(); i++ ) {
--- 2,462 ----
package net.sf.hibernate.cfg;
+ import java.util.Enumeration;
+ import java.util.Iterator;
+ import java.util.ArrayList;
+ import java.util.HashMap;
+ import java.util.Map;
+ import java.util.Properties;
+ import java.util.jar.JarFile;
+ import java.util.zip.ZipEntry;
+ import java.io.IOException;
import java.io.InputStream;
! import java.io.Serializable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
! import org.w3c.dom.Document;
! import org.w3c.dom.NamedNodeMap;
! import org.w3c.dom.Node;
! import org.w3c.dom.NodeList;
! import org.xml.sax.InputSource;
!
! import net.sf.hibernate.util.ArrayHelper;
! import net.sf.hibernate.util.StringHelper;
! import net.sf.hibernate.util.XMLHelper;
! import net.sf.hibernate.HibernateException;
! import net.sf.hibernate.Interceptor;
! import net.sf.hibernate.MappingException;
! import net.sf.hibernate.SessionFactory;
! import net.sf.hibernate.tool.hbm2ddl.JdbcDatabaseInfo;
! import net.sf.hibernate.tool.hbm2ddl.JdbcTableInfo;
! import net.sf.hibernate.type.Type;
! import net.sf.hibernate.id.IdentifierGenerator;
! import net.sf.hibernate.id.PersistentIdentifierGenerator;
! import net.sf.hibernate.impl.SessionFactoryImpl;
! import net.sf.hibernate.mapping.Collection;
! import net.sf.hibernate.mapping.ForeignKey;
! import net.sf.hibernate.mapping.Index;
! import net.sf.hibernate.mapping.PersistentClass;
! import net.sf.hibernate.mapping.Root;
! import net.sf.hibernate.mapping.Table;
! import net.sf.hibernate.dialect.Dialect;
! import net.sf.hibernate.engine.Mapping;
/**
! * NOT threadsafe
*/
!
! public class Configuration implements Mapping {
! private HashMap classes = new HashMap();
! private HashMap collections = new HashMap();
! private HashMap tables = new HashMap();
! private HashMap namedQueries = new HashMap();
! private Interceptor interceptor = EMPTY_INTERCEPTOR;
! private Properties properties = Environment.getProperties();
! private static Log log = LogFactory.getLog(Configuration.class);
! public Type getIdentifierType(Class persistentClass) throws MappingException {
! return ( (PersistentClass) classes.get(persistentClass) ).getIdentifier().getType();
}
! public Iterator getClassMappings() {
! return classes.values().iterator();
}
! public Iterator getCollectionMappings() {
! return collections.values().iterator();
! }
!
! private Iterator getTableMappings() {
! return tables.values().iterator();
! }
!
! public PersistentClass getClassMapping(Class persistentClass) {
! return (PersistentClass) classes.get(persistentClass);
! }
!
! public Configuration addFile(String xmlFile) throws MappingException {
! log.info("Mapping file: " + xmlFile);
! try {
! add( XMLHelper.parseFile(xmlFile) );
! }
! catch (Exception e) {
! log.error("Could not configure datastore from file: " + xmlFile, e);
! throw new MappingException(e);
! }
! return this;
! }
!
! public Configuration addXML(String xml) throws MappingException {
! if ( log.isDebugEnabled() ) log.debug("Mapping XML:\n" + xml);
! try {
! add( XMLHelper.parseString(xml) );
! }
! catch (Exception e) {
! log.error("Could not configure datastore from XML", e);
! throw new MappingException(e);
! }
! return this;
! }
!
! public Configuration addDocument(Document doc) throws MappingException {
! if ( log.isDebugEnabled() ) log.debug("Mapping XML:\n" + doc);
! try {
! add(doc);
! }
! catch (Exception e) {
! log.error("Could not configure datastore from XML document", e);
! throw new MappingException(e);
! }
! return this;
! }
!
! private void add(Document doc) throws Exception {
! try {
! new Root(doc, classes, collections, tables, namedQueries);
! }
! catch (MappingException me) {
! log.error("Could not compile the mapping document", me);
! throw me;
! }
! }
!
! public Configuration addInputStream(InputStream xmlInputStream) throws MappingException {
! try {
! add( XMLHelper.parseInputSource( new InputSource(xmlInputStream) ) );
! return this;
! }
! catch (MappingException me) {
! throw me;
! }
! catch (Exception e) {
! log.error("Could not configure datastore from input stream", e);
! throw new MappingException(e);
! }
! }
!
! public Configuration addResource(String path, ClassLoader classLoader) throws MappingException {
! log.info("Mapping resource: " + path);
! InputStream rsrc = classLoader.getResourceAsStream(path);
! if (rsrc==null) throw new MappingException("Resource: " + path + " not found");
! return addInputStream(rsrc);
! }
!
! public Configuration addClass(Class persistentClass) throws MappingException {
! String fileName = persistentClass.getName().replace(StringHelper.DOT,'/') + ".hbm.xml";
! log.info("Mapping resource: " + fileName);
! InputStream rsrc = persistentClass.getClassLoader().getResourceAsStream(fileName);
! if (rsrc==null) throw new MappingException("Resource: " + fileName + " not found");
! return addInputStream(rsrc);
! }
!
! public Configuration addJar(String resource) throws MappingException {
! log.info("Searching for mapping documents in jar: " + resource);
! final JarFile jarFile;
! try {
! jarFile = new JarFile(
! Thread.currentThread().getContextClassLoader().getResource(resource).getFile()
! );
! }
! catch (IOException ioe) {
! log.error("Could not configure datastore from jar", ioe);
! throw new MappingException(ioe);
! }
!
! if (jarFile==null) throw new MappingException("Resource: " + resource + " not found");
!
! Enumeration enum = jarFile.entries();
! while( enum.hasMoreElements() ) {
!
! ZipEntry z = (ZipEntry) enum.nextElement();
!
! if( z.getName().endsWith(".hbm.xml") ) {
! log.info( "Found mapping documents in jar: " + z.getName() );
! try {
! addInputStream( jarFile.getInputStream(z) );
! }
! catch (MappingException me) {
! throw me;
! }
! catch (Exception e) {
! log.error("Could not configure datastore from jar", e);
! throw new MappingException(e);
! }
! }
}
+ return this;
+
+ }
+
+ private Iterator iterateGenerators(Dialect dialect) throws MappingException {
+ HashMap generators = new HashMap();
+ Iterator iter = classes.values().iterator();
+ while ( iter.hasNext() ) {
+ IdentifierGenerator ig = ( (PersistentClass) iter.next() ).getIdentifier().createIdentifierGenerator(dialect);
+ if ( ig instanceof PersistentIdentifierGenerator ) generators.put(
+ ( (PersistentIdentifierGenerator) ig ).generatorKey(), ig
+ );
+ }
+ return generators.values().iterator();
}
! public String[] generateDropSchemaScript(Dialect dialect) throws HibernateException {
!
! secondPassCompile();
!
! ArrayList script = new ArrayList(50);
!
! if ( dialect.dropConstraints() ) {
! Iterator iter = getTableMappings();
! while ( iter.hasNext() ) {
! Table table = (Table)iter.next();
! Iterator subIter = table.foreignKeyIterator();
! while ( subIter.hasNext() ) {
! ForeignKey fk = (ForeignKey)subIter.next();
! script.add(fk.sqlDropString(dialect));
! }
! }
! }
!
!
! Iterator iter = getTableMappings();
! while ( iter.hasNext() ) {
! Table table = (Table) iter.next();
! script.add( table.sqlDropString(dialect) );
! }
!
! iter = iterateGenerators(dialect);
! while ( iter.hasNext() ) {
! String dropString = ( (PersistentIdentifierGenerator) iter.next() ).sqlDropString(dialect);
! if (dropString!=null) script.add(dropString);
! }
!
! return ArrayHelper.toStringArray(script);
! }
!
! public String[] generateSchemaCreationScript(Dialect dialect) throws HibernateException {
! secondPassCompile();
!
! ArrayList script = new ArrayList(50);
!
! Iterator iter = getTableMappings();
! while ( iter.hasNext() ) {
! Table table = (Table) iter.next();
! script.add( table.sqlCreateString(dialect, this) );
! }
!
! iter = getTableMappings();
! while ( iter.hasNext() ) {
! Table table = (Table) iter.next();
! Iterator subIter;
!
! if ( dialect.hasAlterTable() ) {
! subIter = table.foreignKeyIterator();
! while ( subIter.hasNext() ) {
! ForeignKey fk = (ForeignKey) subIter.next();
! script.add( fk.sqlCreateString(dialect, this) );
! }
! }
!
! subIter = table.indexIterator();
! while ( subIter.hasNext() ) {
! Index index = (Index) subIter.next();
! script.add( index.sqlCreateString(dialect, this) );
! }
! }
!
! iter = iterateGenerators(dialect);
! while ( iter.hasNext() )
! {
! String[] lines = ( (PersistentIdentifierGenerator) iter.next() ).sqlCreateStrings(dialect);
! for ( int i=0; i<lines.length; i++ ) script.add( lines[i] );
! }
!
! return ArrayHelper.toStringArray(script);
! }
!
! public String[] generateSchemaUpdateScript(Dialect dialect, JdbcDatabaseInfo databaseInfo) throws HibernateException {
! secondPassCompile();
!
! ArrayList script = new ArrayList(50);
!
! Iterator iter = getTableMappings();
! while ( iter.hasNext() ) {
! Table table = (Table) iter.next();
! JdbcTableInfo tableInfo = databaseInfo.getTableInfo( table.getName() );
! if (tableInfo == null) {
! script.add( table.sqlCreateString(dialect, this) );
! }
! else {
! final String sql = table.sqlAlterString(dialect, this, tableInfo);
! if (sql!=null) script.add(sql);
! }
! }
!
! iter = getTableMappings();
! while ( iter.hasNext() ) {
! Table table = (Table) iter.next();
! JdbcTableInfo tableInfo = databaseInfo.getTableInfo( table.getName() );
! Iterator subIter;
!
! if ( dialect.hasAlterTable() ) {
! subIter = table.foreignKeyIterator();
! while (subIter.hasNext()) {
! ForeignKey fk = (ForeignKey) subIter.next();
! if ( tableInfo == null || tableInfo.getForeignKeyInfo( fk.getName() ) == null )
! script.add( fk.sqlCreateString(dialect, this) );
! }
! }
!
! subIter = table.indexIterator();
! while ( subIter.hasNext() ) {
! Index index = (Index)subIter.next();
! if ( tableInfo == null || tableInfo.getIndexInfo( index.getName() )==null )
! script.add( index.sqlCreateString(dialect, this) );
! }
! }
!
! iter = iterateGenerators(dialect);
! while ( iter.hasNext() ) {
! PersistentIdentifierGenerator generator = (PersistentIdentifierGenerator) iter.next();
! Object key = generator.generatorKey();
! if ( !databaseInfo.isSequence(key) && !databaseInfo.isTable(key) ) {
! String[] lines = generator.sqlCreateStrings(dialect);
! for (int i = 0; i < lines.length; i++) script.add( lines[i] );
! }
! }
!
! return ArrayHelper.toStringArray(script);
! }
!
! // This method may be called many times!!
! private void secondPassCompile() throws MappingException {
!
! Iterator iter = collections.values().iterator();
! while ( iter.hasNext() ) {
! ( (Collection) iter.next() ).secondPassCompile(classes);
! }
!
! //TODO: Somehow add the newly created foreign keys to the internal collection
!
! iter = getTableMappings();
! while ( iter.hasNext() ) {
! Table table = (Table) iter.next();
! Iterator subIter = table.foreignKeyIterator();
! while ( subIter.hasNext() ) {
!
! ForeignKey fk = (ForeignKey)subIter.next();
! if ( fk.getReferencedTable() == null ) {
! PersistentClass referencedClass = (PersistentClass) classes.get( fk.getReferencedClass() );
! if (referencedClass == null) throw new MappingException(
! "An association refers to an unmapped class: " +
! fk.getReferencedClass().getName()
! );
! fk.setReferencedTable( referencedClass.getTable() );
! }
! }
! }
! }
!
! public Map getNamedQueries() {
! return namedQueries;
! }
!
! private static final Interceptor EMPTY_INTERCEPTOR = new EmptyInterceptor();
!
! public static final class EmptyInterceptor implements Interceptor, Serializable {
! /**
! * @see net.sf.hibernate.Interceptor#onDelete(Object, Serializable id, Object[], String[], Type[])
! */
! public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
! }
!
! /**
! * @see net.sf.hibernate.Interceptor#onFlushDirty(Object, Object[], Object[], String[], Type[])
! */
! public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
! return false;
! }
!
! /**
! * @see net.sf.hibernate.Interceptor#onLoad(Object, Object[], String[], Type[])
! */
! public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
! return false;
! }
!
! /**
! * @see net.sf.hibernate.Interceptor#onSave(Object, Object[], String[], Type[])
! */
! public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
! return false;
! }
!
! /**
! * @see net.sf.hibernate.Interceptor#onPostFlush(Object, Serializable, Object[], String[], Type[])
! */
! public void onPostFlush(Object entity, Serializable id, Object[] currentState, String[] propertyNames, Type[] types) {
! }
!
! /**
! * @see net.sf.hibernate.Interceptor#postFlush(Iterator)
! */
! public void postFlush(Iterator entities) {
! }
!
! /**
! * @see net.sf.hibernate.Interceptor#preFlush(Iterator)
! */
! public void preFlush(Iterator entities) {
! }
!
! /**
! * @see net.sf.hibernate.Interceptor#isUnsaved(java.lang.Object)
! */
! public Boolean isUnsaved(Object entity) {
! return null;
! }
!
! }
!
! public SessionFactory buildSessionFactory() throws HibernateException {
! secondPassCompile();
! Environment.verifyProperties(properties);
! Properties copy = new Properties();
! copy.putAll(properties);
! return new SessionFactoryImpl(this, copy, interceptor);
! }
!
! public Interceptor getInterceptor() {
! return interceptor;
! }
!
! public Properties getProperties() {
! return properties;
! }
!
! public void setInterceptor(Interceptor interceptor) {
! this.interceptor = interceptor;
! }
!
! public void setProperties(Properties properties) {
! this.properties = properties;
! }
!
! public void setProperty(String propertyName, String value) {
! properties.setProperty(propertyName, value);
! }
!
! public String getProperty(String propertyName) {
! return properties.getProperty(propertyName);
! }
!
! private void addProperties(Node parent) {
NodeList children = parent.getChildNodes();
for ( int i=0; i<children.getLength(); i++ ) {
***************
*** 102,112 ****
}
Environment.verifyProperties(properties);
! };
! public SessionFactory[] configure() throws HibernateException {
! ArrayList factories = new ArrayList();
! InputStream stream = getConfigurationInputStream();
Document doc;
--- 471,501 ----
}
Environment.verifyProperties(properties);
! }
! /**
! * Get the configuration file as an <tt>InputStream</tt>. Might be overridden
! * by subclasses to allow the configuration to be located by some arbitrary
! * mechanism.
! */
! protected InputStream getConfigurationInputStream(String resource) throws HibernateException {
! log.info("Configuration resource: " + resource);
! InputStream stream = Environment.class.getResourceAsStream(resource);
! if (stream==null) {
! log.warn(resource + " not found");
! throw new HibernateException(resource + " not found");
! }
! return stream;
!
! }
!
! public void configure() throws HibernateException {
! configure("hibernate.cfg.xml");
! }
!
! public void configure(String resource) throws HibernateException {
!
! InputStream stream = getConfigurationInputStream(resource);
Document doc;
***************
*** 118,174 ****
throw new HibernateException( "Problem parsing configuration " + resource + ": " + e );
}
- Properties topLevelProps = new Properties();
- topLevelProps.putAll( Environment.getProperties() );
- addProperties( doc.getDocumentElement(), topLevelProps );
! NodeList sfElements = doc.getDocumentElement().getElementsByTagName("session-factory");
! for ( int i=0; i<sfElements.getLength(); i++ ) {
! Node sfNode = sfElements.item(i);
! Properties props = (Properties) topLevelProps.clone();
! String name = sfNode.getAttributes().getNamedItem("name").getNodeValue();
! props.put(Environment.SESSION_FACTORY_NAME, name);
! addProperties(sfNode, props);
!
! Datastore ds = Hibernate.createDatastore();
!
! NodeList mapElements = sfNode.getChildNodes();
! for ( int j=0; j<mapElements.getLength(); j++ ) {
! Node mapElement = mapElements.item(j);
! if ( mapElement.getNodeName().equals("mapping") ) {
! NamedNodeMap atts = mapElement.getAttributes();
! Node resource = atts.getNamedItem("resource");
! Node file = atts.getNamedItem("file");
! Node jar = atts.getNamedItem("jar");
! if (resource!=null) {
! log.debug(name + "<-" + resource);
! try {
! ds.storeResource( resource.getNodeValue(), Thread.currentThread().getContextClassLoader() );
! }
! catch (MappingException me) {
! ds.storeResource( resource.getNodeValue(), Environment.class.getClassLoader() );
! }
! }
! else if ( jar!=null ) {
! log.debug(name + "<-" + jar);
! ds.storeJar( jar.getNodeValue() );
}
! else {
! if (file==null) throw new HibernateException("<mapping> element in configuration specifies no attributes");
! log.debug(name + "<-" + file);
! ds.storeFile( file.getNodeValue() );
}
}
}
-
- factories.add( ds.buildSessionFactory(props) );
-
- log.info("Configured SessionFactory: " + name);
- log.debug("properties: " + props);
}
! log.debug("Configuration successful");
- return (SessionFactory[]) factories.toArray( new SessionFactory[ factories.size() ] );
}
}
--- 507,552 ----
throw new HibernateException( "Problem parsing configuration " + resource + ": " + e );
}
! Node sfNode = doc.getDocumentElement();
! String name = sfNode.getAttributes().getNamedItem("name").getNodeValue();
! properties.setProperty(Environment.SESSION_FACTORY_NAME, name);
! addProperties(sfNode);
!
! Configuration ds = new Configuration();
!
! NodeList mapElements = sfNode.getChildNodes();
! for ( int j=0; j<mapElements.getLength(); j++ ) {
! Node mapElement = mapElements.item(j);
! if ( mapElement.getNodeName().equals("mapping") ) {
! NamedNodeMap atts = mapElement.getAttributes();
! Node rsrc = atts.getNamedItem("resource");
! Node file = atts.getNamedItem("file");
! Node jar = atts.getNamedItem("jar");
! if (rsrc!=null) {
! log.debug(name + "<-" + rsrc);
! try {
! ds.addResource( rsrc.getNodeValue(), Thread.currentThread().getContextClassLoader() );
}
! catch (MappingException me) {
! ds.addResource( rsrc.getNodeValue(), Environment.class.getClassLoader() );
}
}
+ else if ( jar!=null ) {
+ log.debug(name + "<-" + jar);
+ ds.addJar( jar.getNodeValue() );
+ }
+ else {
+ if (file==null) throw new HibernateException("<mapping> element in configuration specifies no attributes");
+ log.debug(name + "<-" + file);
+ ds.addFile( file.getNodeValue() );
+ }
}
}
! log.info("Configured SessionFactory: " + name);
! log.debug("properties: " + properties);
}
+
}
--- Datastore.java DELETED ---
|