amberpersistenceunit.java

来自「RESIN 3.2 最新源码」· Java 代码 · 共 1,802 行 · 第 1/3 页

JAVA
1,802
字号
/* * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT.  See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * *   Free Software Foundation, Inc. *   59 Temple Place, Suite 330 *   Boston, MA 02111-1307  USA * * @author Scott Ferguson */package com.caucho.amber.manager;import com.caucho.amber.AmberException;import com.caucho.amber.AmberRuntimeException;import com.caucho.amber.cfg.AmberConfigManager;import com.caucho.amber.cfg.EmbeddableIntrospector;import com.caucho.amber.cfg.EntityMappingsConfig;import com.caucho.amber.cfg.MappedSuperIntrospector;import com.caucho.amber.cfg.NamedNativeQueryConfig;import com.caucho.amber.cfg.SqlResultSetMappingConfig;import com.caucho.amber.entity.AmberCompletion;import com.caucho.amber.entity.AmberEntityHome;import com.caucho.amber.entity.Entity;import com.caucho.amber.entity.EntityItem;import com.caucho.amber.entity.EntityKey;import com.caucho.amber.entity.Listener;import com.caucho.amber.gen.AmberGenerator;import com.caucho.amber.gen.AmberGeneratorImpl;import com.caucho.amber.idgen.IdGenerator;import com.caucho.amber.idgen.SequenceIdGenerator;import com.caucho.amber.query.AbstractQuery;import com.caucho.amber.query.QueryCacheKey;import com.caucho.amber.query.ResultSetCacheChunk;import com.caucho.amber.table.AmberTable;import com.caucho.amber.type.*;import com.caucho.config.ConfigException;import com.caucho.java.gen.JavaClassGenerator;import com.caucho.jdbc.JdbcMetaData;import com.caucho.naming.Jndi;import com.caucho.util.L10N;import com.caucho.util.LruCache;import com.caucho.webbeans.manager.*;import javax.persistence.EntityManager;import javax.sql.DataSource;import java.io.IOException;import java.lang.ref.SoftReference;import java.lang.reflect.Method;import java.sql.ResultSetMetaData;import java.util.*;import java.util.logging.Level;import java.util.logging.Logger;/** * Main interface between Resin and the connector.  It's the * top-level SPI class for creating the SPI ManagedConnections. * * The resource configuration in Resin's web.xml will use bean-style * configuration to configure the ManagecConnectionFactory. */public class AmberPersistenceUnit {  private static final L10N L = new L10N(AmberPersistenceUnit.class);  private static final Logger log    = Logger.getLogger(AmberPersistenceUnit.class.getName());  private String _name;  private boolean _isJPA;  private AmberContainer _amberContainer;  // Actual class is EntityManagerProxy, but EntityManager is JDK 1.5 dependent  private Object _entityManagerProxy;  // basic data source  private DataSource _dataSource;  // data source for read-only requests  private DataSource _readDataSource;  // data source for requests in a transaction  private DataSource _xaDataSource;  private String _jtaDataSourceName;  private String _nonJtaDataSourceName;    // persistence.xml jta-data-source  private DataSource _jtaDataSource;  // persistence.xml non-jta-data-source  private DataSource _nonJtaDataSource;  private JdbcMetaData _jdbcMetaData;  private Boolean _createDatabaseTables;  private boolean _validateDatabaseTables = true;  // private long _tableCacheTimeout = 250;  private long _tableCacheTimeout = 2000;  private TypeManager _typeManager = new TypeManager();  // loader override for ejb  private ClassLoader _enhancedLoader;  private HashMap<String,AmberTable> _tableMap    = new HashMap<String,AmberTable>();  private HashMap<String,AmberEntityHome> _entityHomeMap    = new HashMap<String,AmberEntityHome>();  private HashMap<String,IdGenerator> _tableGenMap    = new HashMap<String,IdGenerator>();  private HashMap<String,SequenceIdGenerator> _sequenceGenMap    = new HashMap<String,SequenceIdGenerator>();  private LruCache<String,AbstractQuery> _queryParseCache    = new LruCache<String,AbstractQuery>(1024);  private LruCache<QueryCacheKey,SoftReference<ResultSetCacheChunk>> _queryCache    = new LruCache<QueryCacheKey,SoftReference<ResultSetCacheChunk>>(1024);  private LruCache<QueryCacheKey,SoftReference<ResultSetMetaData>> _queryCacheMetaData    = new LruCache<QueryCacheKey,SoftReference<ResultSetMetaData>>(16);  private LruCache<EntityKey,SoftReference<EntityItem>> _entityCache    = new LruCache<EntityKey,SoftReference<EntityItem>>(32 * 1024);  private EntityKey _entityKey = new EntityKey();  private ArrayList<EntityType> _lazyConfigure = new ArrayList<EntityType>();  private ArrayList<EntityType> _lazyGenerate = new ArrayList<EntityType>();  private ArrayList<AmberEntityHome> _lazyHomeInit    = new ArrayList<AmberEntityHome>();  private ArrayList<AmberTable> _lazyTable = new ArrayList<AmberTable>();  private HashMap<String,String> _namedQueryMap    = new HashMap<String,String>();  private HashMap<String, SqlResultSetMappingConfig> _sqlResultSetMap    = new HashMap<String, SqlResultSetMappingConfig>();  private HashMap<String, NamedNativeQueryConfig> _namedNativeQueryMap    = new HashMap<String, NamedNativeQueryConfig>();  private ArrayList<EntityMappingsConfig> _entityMappingsList;  private ArrayList<EmbeddableType> _embeddableTypes    = new ArrayList<EmbeddableType>();  private ArrayList<MappedSuperclassType> _mappedSuperclassTypes    = new ArrayList<MappedSuperclassType>();  private ArrayList<ListenerType> _defaultListeners    = new ArrayList<ListenerType>();  private AmberConfigManager _configManager;    private EmbeddableIntrospector _embeddableIntrospector;  private MappedSuperIntrospector _mappedSuperIntrospector;  private AmberGenerator _generator;  // private boolean _supportsGetGeneratedKeys;  private ThreadLocal<AmberConnection> _threadConnection    = new ThreadLocal<AmberConnection>();  private volatile boolean _isInit;  private long _xid = 1;  public AmberPersistenceUnit(AmberContainer container,                              String name)  {    _amberContainer = container;    _name = name;    _dataSource = container.getDataSource();    _xaDataSource = container.getXADataSource();    _readDataSource = container.getReadDataSource();    _configManager = new AmberConfigManager(this);    // needed to support JDK 1.4 compatibility    try {      bindProxy();    } catch (Throwable e) {      log.log(Level.FINE, e.toString(), e);    }  }  public void setName(String name)  {    _name = name;  }  public String getName()  {    return _name;  }  private void bindProxy()    throws Exception  {    String name = getName();    // XXX: is "default" appropriate?    // jpa/0s2m <=> tck: ejb30/persistence/ee/packaging/ejb/resource_local/test1    if (name == null || "".equals(name))      name = "default";    WebBeansContainer webBeans = WebBeansContainer.create(_amberContainer.getParentClassLoader());    webBeans.addSingleton(new AmberEntityManagerFactory(this), name);    webBeans.addSingleton(new EntityManagerProxy(this), name);  }  public EntityManager getEntityManager()  {    // return (EntityManager) _entityManagerProxy;    return null;  }  public AmberContainer getAmberContainer()  {    return _amberContainer;  }    public ClassLoader getTempClassLoader()  {    return _amberContainer.getTempClassLoader();  }  public ClassLoader getEnhancedLoader()  {    if (_enhancedLoader != null)      return _enhancedLoader;    else      return _amberContainer.getEnhancedLoader();  }  /**   * EJB/CMP needs to set a special enhanced loader.   */  public void setEnhancedLoader(ClassLoader loader)  {    _enhancedLoader = loader;  }  /**   * Sets the data source.   */  public void setDataSource(DataSource dataSource)  {    _dataSource = dataSource;  }  /**   * Gets the data source.   */  public DataSource getDataSource()  {    if (_jtaDataSource != null)      return _jtaDataSource;    else if (_nonJtaDataSource != null)      return _nonJtaDataSource;    else if (_dataSource != null)      return _dataSource;    else {      return _amberContainer.getDataSource();    }  }  /**   * Sets the read data source.   */  public void setReadDataSource(DataSource dataSource)  {    _readDataSource = dataSource;  }  /**   * Gets the read data source.   */  public DataSource getReadDataSource()  {    return _readDataSource;  }  /**   * Sets the XA data source.   */  public void setXADataSource(DataSource dataSource)  {    _xaDataSource = dataSource;  }  /**   * Gets the xa data source.   */  public DataSource getXADataSource()  {    return _xaDataSource;  }  /**   * Sets the persistence.xml jta data source.   */  public void setJtaDataSourceName(String name)  {    _jtaDataSourceName = name;  }  /**   * Sets the persistence.xml non-jta data source.   */  public void setNonJtaDataSourceName(String name)  {    _nonJtaDataSourceName = name;  }  /**   * Sets the persistence.xml jta data source.   */  public void setJtaDataSource(DataSource dataSource)  {    _jtaDataSource = dataSource;  }  /**   * Sets the persistence.xml non-jta data source.   */  public void setNonJtaDataSource(DataSource dataSource)  {    _nonJtaDataSource = dataSource;  }  /**   * Return true for a jta-managed persistence unit   */  public boolean isJta()  {    return _nonJtaDataSource == null || _jtaDataSource != null;  }  /**   * Returns the jdbc meta data.   */  public JdbcMetaData getMetaData()  {    if (_jdbcMetaData == null) {      if (getDataSource() == null)        throw new ConfigException("No data-source specified for PersistenceUnit");      _jdbcMetaData = JdbcMetaData.create(getDataSource());    }    return _jdbcMetaData;  }  /**   * Set true if database tables should be created automatically.   */  public void setCreateDatabaseTables(boolean create)  {    _createDatabaseTables = create;  }  /**   * Set true if database tables should be created automatically.   */  public boolean getCreateDatabaseTables()  {    if (_createDatabaseTables != null)      return _createDatabaseTables;    else      return _amberContainer.getCreateDatabaseTables();  }  /**   * Set true if database tables should be validated automatically.   */  public void setValidateDatabaseTables(boolean validate)  {    _validateDatabaseTables = validate;  }  /**   * Set true if database tables should be validated automatically.   */  public boolean getValidateDatabaseTables()  {    return _validateDatabaseTables;  }  /**   * Set the default table cache time.   */  public void setTableCacheTimeout(long timeout)  {    _tableCacheTimeout = timeout;  }  /**   * Get the default table cache time.   */  public long getTableCacheTimeout()  {    return _tableCacheTimeout;  }  /**   * Set false for EJB-style generation.   */  public void setBytecodeGenerator(boolean isBytecodeGenerator)  {    if (isBytecodeGenerator)      _generator = _amberContainer.getGenerator();    else      _generator = new AmberGeneratorImpl(this);  }  /**   * Returns a new xid.   */  public long getXid()  {    synchronized (this) {      return _xid++;    }  }    public Class loadTempClass(String className)  {    try {      return Class.forName(className, false, getTempClassLoader());    } catch (ClassNotFoundException e) {      throw ConfigException.create(e);    }  }  /**   * Creates a table.   */  public AmberTable createTable(String tableName)  {    if (log.isLoggable(Level.FINER))      log.log(Level.FINER, "AmberPersistenceUnit.createTable: " + tableName);    AmberTable table = _tableMap.get(tableName);    if (table == null) {      table = new AmberTable(this, tableName);      table.setCacheTimeout(getTableCacheTimeout());      _tableMap.put(tableName, table);      _lazyTable.add(table);    }    return table;  }  public Throwable getConfigException()  {    return _amberContainer.getConfigException();  }  /**   * Add an entity.   *   * @param className the class name   * @param type the JClass type if it is already verified as an   *             Entity | Embeddable | MappedSuperclass   */  public void addEntityClass(String className,                             Class type)    throws ConfigException  {    if (type == null) {      type = loadTempClass(className);      if (type == null) {        throw new ConfigException(L.l("'{0}' is an unknown type",                                      className));      }    }    BeanType beanType = _configManager.introspect(type);    if (beanType instanceof EntityType)      _amberContainer.addEntity(className, (EntityType) beanType);  }  /**   * Adds a sql result set mapping.   */  public void addSqlResultSetMapping(String resultSetName,                                     SqlResultSetMappingConfig resultSet)    throws ConfigException  {    if (_sqlResultSetMap.containsKey(resultSetName)) {      throw new ConfigException(L.l("SqlResultSetMapping '{0}' is already defined.",                                    resultSetName));    }    _sqlResultSetMap.put(resultSetName, resultSet);  }  /**   * Returns the sql result set mapping.   */  public SqlResultSetMappingConfig getSqlResultSetMapping(String resultSetName)  {    return _sqlResultSetMap.get(resultSetName);  }  /**   * Adds a named query.   */  public void addNamedQuery(String name,                            String query)    throws ConfigException  {    if (_namedQueryMap.containsKey(name)) {      throw new ConfigException(L.l("Named query '{0}': '{1}' is already defined.",                                    name, query));    }    _namedQueryMap.put(name, query);  }  /**   * Returns the named query statement.   */  public String getNamedQuery(String name)  {    return (String) _namedQueryMap.get(name);  }  /**   * Adds a named native query.   */  public void addNamedNativeQuery(String name,                                  NamedNativeQueryConfig queryConfig)    throws ConfigException  {    if (_namedNativeQueryMap.containsKey(name)) {      throw new ConfigException(L.l("NamedNativeQuery '{0}' is already defined.",                                    name));    }    _namedNativeQueryMap.put(name, queryConfig);  }  /**   * Returns the named native query.   */  public NamedNativeQueryConfig getNamedNativeQuery(String name)  {    return _namedNativeQueryMap.get(name);  }  /**   * Adds an entity.   */  public EntityType createEntity(Class beanClass)  {    return createEntity(beanClass.getName(), beanClass);  }  /**   * Adds an entity.   */  public EntityType createEntity(String name,                                 Class beanClass)  {    EntityType entityType = (EntityType) _typeManager.get(name);    if (entityType != null)

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?