org.hibernate.cfg.Configuration类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(15.2k)|赞(0)|评价(0)|浏览(151)

本文整理了Java中org.hibernate.cfg.Configuration类的一些代码示例,展示了Configuration类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Configuration类的具体详情如下:
包路径:org.hibernate.cfg.Configuration
类名称:Configuration

Configuration介绍

[英]Represents one approach for bootstrapping Hibernate. In fact, historically this was the way to bootstrap Hibernate.

The approach here is to define all configuration and mapping sources in one API and to then build the org.hibernate.SessionFactory in one-shot. The configuration and mapping sources defined here are just held here until the SessionFactory is built. This is an important distinction from the legacy behavior of this class, where we would try to incrementally build the mappings from sources as they were added. The ramification of this change in behavior is that users can add configuration and mapping sources here, but they can no longer query the in-flight state of mappings ( org.hibernate.mapping.PersistentClass, org.hibernate.mapping.Collection, etc) here.

Note: Internally this class uses the new bootstrapping approach when asked to build the SessionFactory.
[中]表示一种引导Hibernate的方法。事实上,历史上这是引导休眠的方式。
这里的方法是在一个API中定义所有配置和映射源,然后构建组织。冬眠一次性完成SessionFactory。在构建SessionFactory之前,这里定义的配置和映射源一直保存在这里。这是与此类遗留行为的一个重要区别,在此类遗留行为中,我们将尝试在添加源时从源增量构建映射。这种行为变化的后果是,用户可以在此处添加配置和映射源,但不能再在此处查询映射的运行状态(org.hibernate.mapping.PersistentClass、org.hibernate.mapping.Collection等)。
注意:在内部,当被要求构建SessionFactory时,该类使用新的引导方法。

代码示例

代码示例来源:origin: hibernate/hibernate-orm

@Before
public void buildSessionFactory() {
  Configuration cfg = new Configuration()
      .addAnnotatedClass( TheEntity.class );
  cfg.getProperties().put( AvailableSettings.DIALECT, NoTupleSupportDialect.class.getName() );
  cfg.getProperties().put( AvailableSettings.HBM2DDL_AUTO, "create-drop" );
  sessionFactory = cfg.buildSessionFactory();
}

代码示例来源:origin: hibernate/hibernate-orm

@Test
  public void testAnnReferencesHbm() throws Exception {
    Configuration cfg = new Configuration();
    cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" );
    cfg.addAnnotatedClass( Port.class );
    cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
    SessionFactory sf = cfg.buildSessionFactory();
    assertNotNull( sf );
    Session s = sf.openSession();
    Transaction tx = s.beginTransaction();
    Query q = s.createQuery( "from Boat" );
    assertEquals( 0, q.list().size() );
    q = s.createQuery( "from Port" );
    assertEquals( 0, q.list().size() );
    tx.commit();
    s.close();
    sf.close();
  }
}

代码示例来源:origin: hibernate/hibernate-orm

public static Configuration buildBaseConfiguration() {
  return new Configuration()
      .setProperty( Environment.DRIVER, DRIVER )
      .setProperty( Environment.URL, URL )
      .setProperty( Environment.USER, USER )
      .setProperty( Environment.PASS, PASS )
      .setProperty( Environment.DIALECT, DIALECT.getClass().getName() );
}

代码示例来源:origin: hibernate/hibernate-orm

protected final Configuration buildConfiguration() {
  Configuration cfg = new Configuration().setProperties( buildProperties() );
  String[] mappingFiles = ConfigurationHelper.toStringArray( mapResources, " ,\n\t\r\f" );
  for ( int i = 0; i < mappingFiles.length; i++ ) {
    cfg.addResource( mappingFiles[i] );
  }
  return cfg;
}

代码示例来源:origin: hibernate/hibernate-orm

public void start() {
  Configuration configuration = new Configuration();
  configuration = configuration.configure( "hibernate.cfg.xml" );
  configuration.addAnnotatedClass( WildFlyDdlEntity.class );
  // creating the SF should run schema creation
  sessionFactory = configuration.buildSessionFactory();
}

代码示例来源:origin: org.compass-project/compass

private CompassHolder initCompassHolder(Configuration cfg) {
  Properties compassProperties = new Properties();
  Properties props = cfg.getProperties();
  for (Map.Entry entry : props.entrySet()) {
    String key = (String) entry.getKey();
    if (key.startsWith(COMPASS_PREFIX)) {
      compassProperties.put(entry.getKey(), entry.getValue());
  for (Iterator it = cfg.getClassMappings(); it.hasNext();) {
    PersistentClass clazz = (PersistentClass) it.next();
    Class<?> mappedClass = clazz.getMappedClass();
    for (Iterator propIt = clazz.getPropertyIterator(); propIt.hasNext();) {
      Property prop = (Property) propIt.next();
      Value value = prop.getValue();
    Value idValue = clazz.getIdentifierProperty().getValue();
    if (idValue instanceof Component) {
      Component component = (Component) idValue;
  String transactionFactory = (String) compassProperties.get(CompassEnvironment.Transaction.FACTORY);
  if (transactionFactory == null) {
    String hibernateTransactionStrategy = cfg.getProperty(Environment.TRANSACTION_STRATEGY);
    if (CMTTransactionFactory.class.getName().equals(hibernateTransactionStrategy) || JTATransactionFactory.class.getName().equals(hibernateTransactionStrategy)) {

代码示例来源:origin: org.hibernate/com.springsource.org.hibernate

this.properties = new Properties();
this.properties.putAll( cfg.getProperties() );
this.jdbcServices = this.serviceRegistry.getService( JdbcServices.class );
this.dialect = this.jdbcServices.getDialect();
this.sqlFunctionRegistry = new SQLFunctionRegistry( getDialect(), cfg.getSqlFunctions() );
if ( observer != null ) {
  this.observer.addObserver( observer );
this.typeResolver = cfg.getTypeResolver().scope( this );
this.typeHelper = new TypeLocatorImpl( typeResolver );
this.filters.putAll( cfg.getFilterDefinitions() );
Iterator classes = cfg.getClassMappings();
while ( classes.hasNext() ) {
  PersistentClass model = (PersistentClass) classes.next();
  if ( !model.isInherited() ) {
    IdentifierGenerator generator = model.getIdentifier().createIdentifierGenerator(
        cfg.getIdentifierGeneratorFactory(),
        getDialect(),
        settings.getDefaultCatalogName(),
Map entityAccessStrategies = new HashMap();
Map<String,ClassMetadata> classMeta = new HashMap<String,ClassMetadata>();
classes = cfg.getClassMappings();
while ( classes.hasNext() ) {
  final PersistentClass model = (PersistentClass) classes.next();

代码示例来源:origin: hibernate/hibernate-orm

@Before
public void setup(){
  cfg=new Configuration();
  Properties p = new Properties();
  p.put( Environment.DIALECT, "org.hibernate.dialect.HSQLDialect" );
  p.put( "hibernate.connection.driver_class", "org.h2.Driver" );
  p.put( "hibernate.connection.url", "jdbc:h2:mem:" );
  p.put( "hibernate.connection.username", "sa" );
  p.put( "hibernate.connection.password", "" );
  cfg.setProperties(p);
  serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( cfg.getProperties() );
}

代码示例来源:origin: hibernate/hibernate-orm

@Override
  public void configure(Configuration cfg) {
    super.configure( cfg );
    if ( !useAntlrParser ) {
      cfg.setProperty( Environment.QUERY_TRANSLATOR, ClassicQueryTranslatorFactory.class.getName() );
      try {
        String dialectTrueRepresentation = Dialect.getDialect().toBooleanValueString( true );
        // if this call succeeds, then the dialect is saying to represent true/false as int values...
        Integer.parseInt( dialectTrueRepresentation );
        String subs = cfg.getProperties().getProperty( Environment.QUERY_SUBSTITUTIONS );
        if ( subs == null ) {
          subs = "";
        }
        if ( StringHelper.isEmpty( subs ) ) {
          subs = "true=1, false=0";
        }
        else {
          subs += ", true=1, false=0";
        }
        cfg.getProperties().setProperty( Environment.QUERY_SUBSTITUTIONS, subs );
//                cfg.setNamingStrategy( DefaultNamingStrategy.INSTANCE );
      }
      catch( NumberFormatException nfe ) {
        // the Integer#parseInt call failed...
      }
    }
    cfg.setProperty( AvailableSettings.JDBC_TYLE_PARAMS_ZERO_BASE, "true" );
  }

代码示例来源:origin: hibernate/hibernate-orm

@Override
protected void configure(Configuration configuration) {
  Properties properties = configuration.getProperties();
  properties.put( "hibernate.id.new_generator_mappings", "true" );
}

代码示例来源:origin: hibernate/hibernate-orm

protected StandardServiceRegistryImpl buildServiceRegistry(BootstrapServiceRegistry bootRegistry, Configuration configuration) {
  Properties properties = new Properties();
  properties.putAll( configuration.getProperties() );
  ConfigurationHelper.resolvePlaceHolders( properties );
  StandardServiceRegistryBuilder cfgRegistryBuilder = configuration.getStandardServiceRegistryBuilder();
  StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder( bootRegistry, cfgRegistryBuilder.getAggregatedCfgXml() )
      .applySettings( properties );
  prepareBasicRegistryBuilder( registryBuilder );
  return (StandardServiceRegistryImpl) registryBuilder.build();
}

代码示例来源:origin: jboss.jboss-embeddable-ejb3/hibernate-all

this.properties = new Properties();
this.properties.putAll( cfg.getProperties() );
this.interceptor = cfg.getInterceptor();
this.settings = settings;
this.sqlFunctionRegistry = new SQLFunctionRegistry(settings.getDialect(), cfg.getSqlFunctions());
this.eventListeners = listeners;
this.filters = new HashMap();
this.filters.putAll( cfg.getFilterDefinitions() );
Iterator classes = cfg.getClassMappings();
while ( classes.hasNext() ) {
  PersistentClass model = (PersistentClass) classes.next();
  if ( !model.isInherited() ) {
    IdentifierGenerator generator = model.getIdentifier().createIdentifierGenerator(
        settings.getDialect(),
        settings.getDefaultCatalogName(),
entityPersisters = new HashMap();
Map classMeta = new HashMap();
classes = cfg.getClassMappings();
while ( classes.hasNext() ) {
  PersistentClass model = (PersistentClass) classes.next();
Iterator collections = cfg.getCollectionMappings();
while ( collections.hasNext() ) {
  Collection model = (Collection) collections.next();
namedQueries = new HashMap( cfg.getNamedQueries() );
namedSqlQueries = new HashMap( cfg.getNamedSQLQueries() );

代码示例来源:origin: org.hibernate/com.springsource.org.hibernate.ejb

final EventListenerRegistry eventListenerRegistry = serviceRegistry.getService( EventListenerRegistry.class );
boolean isSecurityEnabled = configuration.getProperties().containsKey( AvailableSettings.JACC_ENABLED );
  final String jaccContextId = configuration.getProperty( Environment.JACC_CONTEXTID );
  eventListenerRegistry.prependListeners( EventType.PRE_DELETE, new JACCPreDeleteEventListener(jaccContextId) );
  eventListenerRegistry.prependListeners( EventType.PRE_INSERT, new JACCPreInsertEventListener(jaccContextId) );
eventListenerRegistry.prependListeners( EventType.POST_UPDATE, new EJB3PostUpdateEventListener() );
for ( Map.Entry<?,?> entry : configuration.getProperties().entrySet() ) {
  if ( ! String.class.isInstance( entry.getKey() ) ) {
    continue;
Iterator classes = configuration.getClassMappings();
ReflectionManager reflectionManager = configuration.getReflectionManager();
while ( classes.hasNext() ) {
  PersistentClass clazz = (PersistentClass) classes.next();
  if ( clazz.getClassName() == null ) {
    callbackHandler.add( reflectionManager.classForName( clazz.getClassName(), this.getClass() ), reflectionManager );
    throw new MappingException( "entity class not found: " + clazz.getNodeName(), e );

代码示例来源:origin: hibernate/hibernate-orm

@BeforeClass
public static void buildSessionFactory() {
  Configuration cfg = new Configuration();
  cfg.setProperty( AvailableSettings.DIALECT, DIALECT.getClass().getName() );
  ServiceRegistry serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( cfg.getProperties() );
  SESSION_FACTORY = (SessionFactoryImplementor) cfg.buildSessionFactory( serviceRegistry );
}

代码示例来源:origin: de.tudarmstadt.ukp.uby/de.tudarmstadt.ukp.uby.persistence.transform-asl

public static void dropTables(final DBConfig dbConfig) {
  System.out.println("DROP TABLES");
  Configuration cfg = HibernateConnect.getConfiguration(dbConfig);
  cfg.setProperty("hibernate.hbm2ddl.auto", "none");
  SessionFactory sf = cfg.buildSessionFactory(
      new ServiceRegistryBuilder().applySettings(
      cfg.getProperties()).buildServiceRegistry());
  Session session = sf.openSession();
  Transaction tx = session.beginTransaction();
  try {
    Iterator<Table> iter = cfg.getTableMappings();
    while (iter.hasNext())
      dropSQL.add("DROP TABLE " + iter.next().getName());

代码示例来源:origin: hibernate/hibernate-orm

@Test
public void testQuery() {
  Configuration cfg = new Configuration();		
  cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
  cfg.addInputStream(new ReaderInputStream(new StringReader(NAMED_QUERY_HBM_XML)));
  SessionFactory sessionFactory = cfg.buildSessionFactory();
  sessionFactory.close();
}

代码示例来源:origin: bonitasoft/bonita-engine

configuration = hbmConfigurationProvider.getConfiguration();
  if (extraHibernateProperties != null) {
    configuration.addProperties(extraHibernateProperties);
final String dialect = configuration.getProperty("hibernate.dialect");
OrderByBuilder orderByBuilder = new DefaultOrderByBuilder();
    configuration.setInterceptor(new PostgresInterceptor());
    configuration.registerTypeOverride(new PostgresMaterializedBlobType());
    configuration.registerTypeOverride(new PostgresMaterializedClobType());
    configuration.registerTypeOverride(new PostgresXMLType());
    queryBuilderFactory.setVendor(POSTGRES);
  } else if (dialect.toLowerCase().contains("sqlserver")) {
    SQLServerInterceptor sqlServerInterceptor = new SQLServerInterceptor();
    configuration.setInterceptor(sqlServerInterceptor);
    configuration.registerTypeOverride(new XMLType());
    orderByBuilder = new SQLServerOrderByBuilder();
    queryBuilderFactory.setVendor(SQLSERVER);
  } else if (dialect.toLowerCase().contains("oracle")) {
    configuration.registerTypeOverride(new XMLType());
    queryBuilderFactory.setVendor(ORACLE);
  } else if (dialect.toLowerCase().contains("mysql")) {
    configuration.registerTypeOverride(new XMLType());
    queryBuilderFactory.setVendor(MYSQL);
  }else{
    configuration.registerTypeOverride(new XMLType());
final String className = configuration.getProperty("hibernate.interceptor");
if (className != null && !className.isEmpty()) {

代码示例来源:origin: hibernate/hibernate-orm

@Before
public void beforeTest() {
  Configuration cfg = new Configuration()
      .addAnnotatedClass( Item.class )
      .setProperty( AvailableSettings.HBM2DDL_AUTO, "create-drop" );
  cfg.addAuxiliaryDatabaseObject( ProcedureDefinitions.INSTANCE );
  sf = cfg.buildSessionFactory();
}

代码示例来源:origin: com.blazebit/blaze-persistence-integration-hibernate-4.3

@Override
public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
  Class<?> valuesEntity;
  boolean registerValuesEntity = true;
  try {
    valuesEntity = Class.forName("com.blazebit.persistence.impl.function.entity.ValuesEntity");
  } catch (ClassNotFoundException e) {
    throw new RuntimeException("Are you missing blaze-persistence-core-impl on the classpath?", e);
  }
  Iterator<PersistentClass> iter = configuration.getClassMappings();
  while (iter.hasNext()) {
    PersistentClass clazz = iter.next();
    Class<?> entityClass = clazz.getMappedClass();
    
    if (entityClass != null && entityClass.isAnnotationPresent(CTE.class)) {
      clazz.getTable().setSubselect("select * from " + clazz.getJpaEntityName());
    }
  }
  if (registerValuesEntity) {
    // Register values entity if wasn't found
    configuration.addAnnotatedClass(valuesEntity);
    configuration.buildMappings();
    PersistentClass clazz = configuration.getClassMapping(valuesEntity.getName());
    clazz.getTable().setSubselect("select * from " + clazz.getJpaEntityName());
  }
  serviceRegistry.locateServiceBinding(PersisterClassResolver.class).setService(new CustomPersisterClassResolver());
  serviceRegistry.locateServiceBinding(Database.class).setService(new SimpleDatabase(configuration.getTableMappings(), sessionFactory.getDialect(), new SimpleTableNameFormatter(), configuration.buildMapping()));
}

代码示例来源:origin: Impetus/Kundera

conf.setProperty("hibernate.max_fetch_depth", "0");
    if (value instanceof String)
      conf.setProperty(key, (String) value);
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
    conf.addAnnotatedClass(c);
sf = conf.buildSessionFactory(serviceRegistry);
String schemaProperty = conf.getProperty("hibernate.hbm2ddl.auto");
if (schemaProperty != null && (schemaProperty.equals("create") || schemaProperty.equals("create-drop")))
      StatelessSession session = sf.openStatelessSession();
      if (!pu.equals(getPersistenceUnit()))

相关文章

Configuration类方法