Java Code Examples for org.hibernate.cfg.Configuration#addAnnotatedClass()

The following examples show how to use org.hibernate.cfg.Configuration#addAnnotatedClass() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: ignite   File: HibernateL2CacheSelfTest.java    License: Apache License 2.0 7 votes vote down vote up
/**
 * @param accessType Hibernate L2 cache access type.
 * @param igniteInstanceName Ignite instance name.
 * @return Hibernate configuration.
 */
private Configuration hibernateConfiguration(AccessType accessType,
    String igniteInstanceName) {
    Configuration cfg = new Configuration();

    cfg.addAnnotatedClass(Entity.class);
    cfg.addAnnotatedClass(Entity2.class);
    cfg.addAnnotatedClass(VersionedEntity.class);
    cfg.addAnnotatedClass(ChildEntity.class);
    cfg.addAnnotatedClass(ParentEntity.class);

    cfg.setCacheConcurrencyStrategy(ENTITY_NAME, accessType.getExternalName());
    cfg.setCacheConcurrencyStrategy(ENTITY2_NAME, accessType.getExternalName());
    cfg.setCacheConcurrencyStrategy(VERSIONED_ENTITY_NAME, accessType.getExternalName());
    cfg.setCacheConcurrencyStrategy(PARENT_ENTITY_NAME, accessType.getExternalName());
    cfg.setCollectionCacheConcurrencyStrategy(CHILD_COLLECTION_REGION, accessType.getExternalName());

    for (Map.Entry<String, String> e : hibernateProperties(igniteInstanceName, accessType.name()).entrySet())
        cfg.setProperty(e.getKey(), e.getValue());

    // Use the same cache for Entity and Entity2.
    cfg.setProperty(REGION_CACHE_PROPERTY + ENTITY2_NAME, ENTITY_NAME);

    return cfg;
}
 
Example 2
private static SessionFactory createSessionFactory() {
    try {
        Configuration configuration = configuration();
        configuration.setProperty(AvailableSettings.DIALECT, MySQLDialect.class.getName());
        configuration.setProperty(AvailableSettings.USE_QUERY_CACHE, "false");
        configuration.setProperty(AvailableSettings.SHOW_SQL, "false");
        configuration.setProperty(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, "thread");
        configuration.setProperty("hibernate.hikari.maximumPoolSize", String.valueOf(Runtime.getRuntime().availableProcessors() * 2));
        configuration.addAnnotatedClass(World.class);
        configuration.addAnnotatedClass(Fortune.class);
        StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        return configuration.buildSessionFactory(serviceRegistryBuilder.build());
    } catch (RuntimeException ex) {
        LOGGER.error("Failed to create session factory");
        throw ex;
    }
}
 
Example 3
Source Project: tutorials   File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate-annotation.cfg.xml
        Configuration configuration = new Configuration();
        configuration.addAnnotatedClass(Employee.class);
        configuration.addAnnotatedClass(Project.class);
        configuration.configure("manytomany.cfg.xml");
        System.out.println("Hibernate Annotation Configuration loaded");

        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
            .build();
        System.out.println("Hibernate Annotation serviceRegistry created");

        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        return sessionFactory;
    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example 4
Source Project: flux   File: ShardModule.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds annotated classes and custom types to passed Hibernate configuration.
 */

private void addAnnotatedClassesAndTypes(Configuration configuration) {
    //register hibernate custom types
    configuration.registerTypeOverride(new BlobType(), new String[]{"BlobType"});
    configuration.registerTypeOverride(new StoreFQNType(), new String[]{"StoreFQNOnly"});
    configuration.registerTypeOverride(new ListJsonType(), new String[]{"ListJsonType"});

    //add annotated classes to configuration
    configuration.addAnnotatedClass(AuditRecord.class);
    configuration.addAnnotatedClass(Event.class);
    configuration.addAnnotatedClass(State.class);
    configuration.addAnnotatedClass(StateMachine.class);
    configuration.addAnnotatedClass(ClientElb.class);

}
 
Example 5
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.addAnnotatedClass( AnEntity.class );
	configuration.addAnnotatedClass( OtherEntity.class );
	return configuration;
}
 
Example 6
protected Configuration getConfiguration(Properties prop) {
    Configuration config = new Configuration();
    Properties properties = new Properties();
    properties.putAll(getDefaultProperties());
    if (prop != null) {
        properties.putAll(prop);
    }
    config.setProperties(properties);

    config.addAnnotatedClass(Person.class);
    config.addAnnotatedClass(Contact.class);
    config.addAnnotatedClass(Book.class);

    return config;
}
 
Example 7
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.setProperty( Settings.URL, DatabaseConfiguration.getJdbcUrl() );
	configuration.addAnnotatedClass( Basic.class );
	return configuration;
}
 
Example 8
Source Project: HibernateDemos   File: ValueGenerationDemo.java    License: The Unlicense 5 votes vote down vote up
public static void main(String[] args) {
	final Configuration configuration = new Configuration();
	configuration.addAnnotatedClass( Project.class );
	
	// necessary for a known bug, to be fixed in 4.2.9.Final
	configuration.setProperty( AvailableSettings.USE_NEW_ID_GENERATOR_MAPPINGS, "true" );
	
	final SessionFactory sessionFactory = configuration.buildSessionFactory(
			new StandardServiceRegistryBuilder().build() );
	Session s = sessionFactory.openSession();
	
	final Project project = new Project();
	
	s.getTransaction().begin();
	s.persist(project);
	s.getTransaction().commit();
	s.clear();
	
	System.out.println(project.toString());
	
	s.getTransaction().begin();
	s.update(project );
	s.getTransaction().commit();
	s.close();
	
	System.out.println(project.toString());
	
	System.exit(0);
}
 
Example 9
Source Project: flux   File: SchedulerModule.java    License: Apache License 2.0 5 votes vote down vote up
private void addAnnotatedClassesAndTypes(Configuration configuration) {
    //register hibernate custom types
    configuration.registerTypeOverride(new BlobType(), new String[]{"BlobType"});
    configuration.registerTypeOverride(new StoreFQNType(), new String[]{"StoreFQNOnly"});
    configuration.registerTypeOverride(new ListJsonType(), new String[]{"ListJsonType"});

    configuration.addAnnotatedClass(ScheduledMessage.class);
    configuration.addAnnotatedClass(ScheduledEvent.class);
    configuration.addAnnotatedClass(ClientElb.class);
}
 
Example 10
Source Project: HibernateDemos   File: AbstractDemo.java    License: The Unlicense 5 votes vote down vote up
protected AbstractDemo(Class<?>... entities) {
	final Configuration configuration = new Configuration();
	for (Class<?> entity : entities) {
		configuration.addAnnotatedClass( entity );
	}
	sessionFactory = configuration.buildSessionFactory(
			new StandardServiceRegistryBuilder().build() );
}
 
Example 11
protected void addMappings(Configuration configuration) {
  String[] mappings = getMappings();
  if ( mappings != null ) {
    for ( String mapping : mappings ) {
      configuration.addResource(
          getBaseForMappings() + mapping,
          getClass().getClassLoader()
      );
    }
  }
  Class<?>[] annotatedClasses = getAnnotatedClasses();
  if ( annotatedClasses != null ) {
    for ( Class<?> annotatedClass : annotatedClasses ) {
      configuration.addAnnotatedClass( annotatedClass );
    }
  }
  String[] annotatedPackages = getAnnotatedPackages();
  if ( annotatedPackages != null ) {
    for ( String annotatedPackage : annotatedPackages ) {
      configuration.addPackage( annotatedPackage );
    }
  }
  String[] xmlFiles = getXmlFiles();
  if ( xmlFiles != null ) {
    for ( String xmlFile : xmlFiles ) {
      try ( InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFile ) ) {
        configuration.addInputStream( is );
      }
      catch (IOException e) {
        throw new IllegalArgumentException( e );
      }
    }
  }
}
 
Example 12
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.addAnnotatedClass( GuineaPig.class );
	return configuration;
}
 
Example 13
Source Project: HibernateDemos   File: SpatialDemo.java    License: The Unlicense 4 votes vote down vote up
public SpatialDemo() {
	final Configuration configuration = new Configuration();
	configuration.addAnnotatedClass( Project.class );
	sessionFactory = configuration.buildSessionFactory(
			new StandardServiceRegistryBuilder().build() );
}
 
Example 14
Source Project: coditori   File: Utils.java    License: Apache License 2.0 4 votes vote down vote up
public static SessionFactory getSessionFactory() {
        Configuration configuration = new Configuration();
//        configuration.addResource("customer.hbm.xml");
        configuration.addAnnotatedClass(com.massoudafrashteh.code.hibernate.model.User.class);
        return configuration.buildSessionFactory();
    }
 
Example 15
/**
 * Used only for testing purposes of the hibernate config needs to be changed.
 * RMDBManager.getInstance() should be used in most of cases.
 */
public RMDBManager(Configuration configuration, boolean drop, boolean dropNS) {
    try {
        configuration.addAnnotatedClass(Alive.class);
        configuration.addAnnotatedClass(LockHistory.class);
        configuration.addAnnotatedClass(NodeHistory.class);
        configuration.addAnnotatedClass(NodeSourceData.class);
        configuration.addAnnotatedClass(UserHistory.class);
        configuration.addAnnotatedClass(RMNodeData.class);
        if (drop) {
            configuration.setProperty("hibernate.hbm2ddl.auto", "create");

            // dropping RRD database as well
            File ddrDB = new File(PAResourceManagerProperties.getAbsolutePath(PAResourceManagerProperties.RM_RRD_DATABASE_NAME.getValueAsString()));

            if (ddrDB.exists() && !ddrDB.delete()) {
                logger.error("Dropping RRD database has failed: " + ddrDB);
            }
        }

        configuration.setProperty("hibernate.id.new_generator_mappings", "true");
        configuration.setProperty("hibernate.jdbc.use_streams_for_binary", "true");

        sessionFactory = configuration.buildSessionFactory();
        transactionHelper = new TransactionHelper(sessionFactory);
        rmdbManagerBuffer = new RMDBManagerBuffer(this);

        Alive lastAliveTimeResult = findRmLastAliveEntry();

        if (lastAliveTimeResult == null) {
            createRmAliveEntry();
        } else if (!drop) {
            if (dropNS) {
                removeNodeSources();
            }

            recover(lastAliveTimeResult.getTime());
        }

        long periodInMilliseconds = PAResourceManagerProperties.RM_ALIVE_EVENT_FREQUENCY.getValueAsLong();

        timer = new Timer("Periodic RM live event saver");
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                updateRmAliveTime();
            }
        }, periodInMilliseconds, periodInMilliseconds);

        // Start house keeping of node history
        startHouseKeeping();

    } catch (Throwable ex) {
        logger.error("Initial SessionFactory creation failed", ex);
        throw new DatabaseManagerException("Initial SessionFactory creation failed", ex);
    }
}
 
Example 16
Source Project: hibernate-types   File: AbstractTest.java    License: Apache License 2.0 4 votes vote down vote up
private SessionFactory newLegacySessionFactory() {
    Properties properties = properties();
    Configuration configuration = new Configuration().addProperties(properties);
    for (Class<?> entityClass : entities()) {
        configuration.addAnnotatedClass(entityClass);
    }
    String[] packages = packages();
    if (packages != null) {
        for (String scannedPackage : packages) {
            configuration.addPackage(scannedPackage);
        }
    }
    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            configuration.addResource(resource);
        }
    }
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.setInterceptor(interceptor);
    }

    final List<Type> additionalTypes = additionalTypes();
    if (additionalTypes != null) {
        configuration.registerTypeContributor(new TypeContributor() {
            @Override
            public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
                for (Type type : additionalTypes) {
                    if (type instanceof BasicType) {
                        typeContributions.contributeType((BasicType) type);
                    } else if (type instanceof UserType) {
                        typeContributions.contributeType((UserType) type);
                    } else if (type instanceof CompositeUserType) {
                        typeContributions.contributeType((CompositeUserType) type);
                    }
                }
            }
        });
    }
    return configuration.buildSessionFactory(
            new StandardServiceRegistryBuilder()
                    .applySettings(properties)
                    .build()
    );
}
 
Example 17
@Override
protected Configuration constructConfiguration() {
	Configuration configuration = super.constructConfiguration();
	configuration.addAnnotatedClass( Basic.class );
	return configuration;
}
 
Example 18
Source Project: hibernate-types   File: AbstractTest.java    License: Apache License 2.0 4 votes vote down vote up
private SessionFactory newLegacySessionFactory() {
    Properties properties = properties();
    Configuration configuration = new Configuration().addProperties(properties);
    for (Class<?> entityClass : entities()) {
        configuration.addAnnotatedClass(entityClass);
    }
    String[] packages = packages();
    if (packages != null) {
        for (String scannedPackage : packages) {
            configuration.addPackage(scannedPackage);
        }
    }
    String[] resources = resources();
    if (resources != null) {
        for (String resource : resources) {
            configuration.addResource(resource);
        }
    }
    Interceptor interceptor = interceptor();
    if (interceptor != null) {
        configuration.setInterceptor(interceptor);
    }

    final List<Type> additionalTypes = additionalTypes();
    if (additionalTypes != null) {
        configuration.registerTypeContributor((typeContributions, serviceRegistry) -> {
            additionalTypes.stream().forEach(type -> {
                if (type instanceof BasicType) {
                    typeContributions.contributeType((BasicType) type);
                } else if (type instanceof UserType) {
                    typeContributions.contributeType((UserType) type);
                } else if (type instanceof CompositeUserType) {
                    typeContributions.contributeType((CompositeUserType) type);
                }
            });
        });
    }
    return configuration.buildSessionFactory(
            new StandardServiceRegistryBuilder()
                    .applySettings(properties)
                    .build()
    );
}
 
Example 19
Source Project: hibernate-demos   File: SpatialDemo.java    License: Apache License 2.0 4 votes vote down vote up
public SpatialDemo() {
	final Configuration configuration = new Configuration();
	configuration.addAnnotatedClass( Project.class );
	sessionFactory = configuration.buildSessionFactory(
			new StandardServiceRegistryBuilder().build() );
}
 
Example 20
/**
 * @param igniteInstanceName Ignite instance name.
 * @return Hibernate configuration.
 */
protected Configuration hibernateConfiguration(String igniteInstanceName) {
    Configuration cfg = new Configuration();

    cfg.addAnnotatedClass(Entity1.class);
    cfg.addAnnotatedClass(Entity2.class);
    cfg.addAnnotatedClass(Entity3.class);
    cfg.addAnnotatedClass(Entity4.class);

    cfg.setProperty(DFLT_ACCESS_TYPE_PROPERTY, AccessType.NONSTRICT_READ_WRITE.name());

    cfg.setProperty(HBM2DDL_AUTO, "create");

    cfg.setProperty(GENERATE_STATISTICS, "true");

    cfg.setProperty(USE_SECOND_LEVEL_CACHE, "true");

    cfg.setProperty(USE_QUERY_CACHE, "true");

    cfg.setProperty(CACHE_REGION_FACTORY, HibernateRegionFactory.class.getName());

    cfg.setProperty(RELEASE_CONNECTIONS, "on_close");

    cfg.setProperty(IGNITE_INSTANCE_NAME_PROPERTY, igniteInstanceName);

    cfg.setProperty(REGION_CACHE_PROPERTY + ENTITY1_NAME, "cache1");
    cfg.setProperty(REGION_CACHE_PROPERTY + ENTITY2_NAME, "cache2");
    cfg.setProperty(REGION_CACHE_PROPERTY + TIMESTAMP_CACHE, TIMESTAMP_CACHE);
    cfg.setProperty(REGION_CACHE_PROPERTY + QUERY_CACHE, QUERY_CACHE);

    return cfg;
}