Java Code Examples for org.hibernate.boot.Metadata

The following are top voted examples for showing how to use org.hibernate.boot.Metadata. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spanner-hibernate   File: CloudSpannerTableExporter.java   View source code 6 votes vote down vote up
@Override
public String[] getSqlDropStrings(Table table, Metadata metadata)
{
	// Check for actually existing table and indices.
	if (!tableExists(table))
		return new String[] {};
	Set<String> existingIndices = getIndicesExcludingPK(table);

	if (existingIndices.isEmpty())
		return super.getSqlDropStrings(table, metadata);

	List<String> dropIndices = new ArrayList<>();
	for (String index : existingIndices)
	{
		dropIndices.add("DROP INDEX `" + index + "`");
	}
	String[] tableDrop = super.getSqlDropStrings(table, metadata);

	String[] res = new String[dropIndices.size() + tableDrop.length];
	dropIndices.toArray(res);
	System.arraycopy(tableDrop, 0, res, dropIndices.size(), tableDrop.length);

	return res;
}
 
Example 2
Project: spanner-hibernate   File: CloudSpannerUniqueDelegate.java   View source code 6 votes vote down vote up
@Override
public String getAlterTableToDropUniqueKeyCommand(UniqueKey uniqueKey, Metadata metadata)
{
	// First check that this unique key actually is present, as this is a
	// lot faster than trying to drop it and then fail.
	initIndices();
	UniqueIndex idx = indices.getIndex(uniqueKey);
	if (idx == null)
	{
		return null;
	}
	// Remove from cache
	indices.removeIndex(uniqueKey);
	final StringBuilder buf = new StringBuilder("DROP INDEX ");
	buf.append(dialect.quote(uniqueKey.getName()));

	return buf.toString();
}
 
Example 3
Project: gitplex-mit   File: DefaultPersistManager.java   View source code 6 votes vote down vote up
protected void applyConstraints(Metadata metadata) {
	File tempFile = null;
   	try {
       	tempFile = File.createTempFile("schema", ".sql");
       	new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
       			.setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);
       	List<String> sqls = new ArrayList<>();
       	for (String sql: FileUtils.readLines(tempFile)) {
       		if (isApplyingConstraints(sql)) {
       			sqls.add(sql);
       		}
       	}
       	execute(sqls, true);
   	} catch (IOException e) {
   		throw new RuntimeException(e);
   	} finally {
   		if (tempFile != null)
   			tempFile.delete();
   	}
}
 
Example 4
Project: gitplex-mit   File: DefaultPersistManager.java   View source code 6 votes vote down vote up
protected void createTables(Metadata metadata) {
	File tempFile = null;
   	try {
       	tempFile = File.createTempFile("schema", ".sql");
       	new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
       			.setFormat(false).createOnly(EnumSet.of(TargetType.SCRIPT), metadata);
       	List<String> sqls = new ArrayList<>();
       	for (String sql: FileUtils.readLines(tempFile)) {
       		if (shouldInclude(sql) && !isApplyingConstraints(sql))
       			sqls.add(sql);
       	}
       	execute(sqls, true);
   	} catch (IOException e) {
   		throw new RuntimeException(e);
   	} finally {
   		if (tempFile != null)
   			FileUtils.deleteFile(tempFile);
   	}
}
 
Example 5
Project: gitplex-mit   File: DefaultPersistManager.java   View source code 6 votes vote down vote up
protected void dropConstraints(Metadata metadata) {
	File tempFile = null;
   	try {
       	tempFile = File.createTempFile("schema", ".sql");
       	new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
       			.setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata);
       	List<String> sqls = new ArrayList<>();
       	for (String sql: FileUtils.readLines(tempFile)) {
       		if (isDroppingConstraints(sql))
       			sqls.add(sql);
       	}
       	execute(sqls, false);
   	} catch (IOException e) {
   		throw new RuntimeException(e);
   	} finally {
   		if (tempFile != null)
   			tempFile.delete();
   	}
}
 
Example 6
Project: gitplex-mit   File: DefaultPersistManager.java   View source code 6 votes vote down vote up
protected void cleanDatabase(Metadata metadata) {
	File tempFile = null;
   	try {
       	tempFile = File.createTempFile("schema", ".sql");
       	new SchemaExport().setOutputFile(tempFile.getAbsolutePath())
       			.setFormat(false).drop(EnumSet.of(TargetType.SCRIPT), metadata);
       	List<String> sqls = new ArrayList<>();
       	for (String sql: FileUtils.readLines(tempFile)) {
       		sqls.add(sql);
       	}
       	execute(sqls, false);
   	} catch (IOException e) {
   		throw new RuntimeException(e);
   	} finally {
   		if (tempFile != null)
   			tempFile.delete();
   	}
}
 
Example 7
Project: gitplex-mit   File: CleanDBCommand.java   View source code 6 votes vote down vote up
@Override
public void start() {
	if (Bootstrap.isServerRunning(Bootstrap.installDir)) {
		logger.error("Please stop server before cleaning database");
		System.exit(1);
	}
	checkDataVersion(false);

	Metadata metadata = buildMetadata();
	cleanDatabase(metadata);

	if (getDialect().toLowerCase().contains("hsql")) {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
		}
	}
	logger.info("Database is cleaned successfully");
	
	System.exit(0);
}
 
Example 8
Project: ipf-flow-manager   File: CustomEventRegistration.java   View source code 6 votes vote down vote up
@Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
    EventListenerRegistry service = serviceRegistry.getService(org.hibernate.event.service.spi.EventListenerRegistry.class);

    StandardPBEStringEncryptor encrypt = new StandardPBEStringEncryptor();
    encrypt.setPassword("test_password");
    RenderedMessageEncryptEventListener encryptListener = new RenderedMessageEncryptEventListener();
    encryptListener.setStringEncryptor(encrypt);

    RenderedMessageDecryptEventListener decryptListener = new RenderedMessageDecryptEventListener();
    decryptListener.setStringEncryptor(encrypt);

    FullTextIndexEventListener fullTextListener = new FullTextIndexEventListener();

    service.appendListeners(EventType.PRE_UPDATE, encryptListener);
    service.prependListeners(EventType.POST_UPDATE, decryptListener);
    service.appendListeners(EventType.PRE_INSERT, encryptListener);
    service.prependListeners(EventType.POST_INSERT, decryptListener);
    service.appendListeners(EventType.POST_LOAD, decryptListener);
}
 
Example 9
Project: VoxelGamesLib   File: HibernatePersistenceProvider.java   View source code 6 votes vote down vote up
@Override
public void start() {
    StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.connection.username", config.persistence.user)
            .applySetting("hibernate.connection.password", config.persistence.pass)
            .applySetting("hibernate.connection.driver_class", config.persistence.driver)
            .applySetting("hibernate.connection.url", config.persistence.url)
            .applySetting("hibernate.dialect", config.persistence.dialect)
            .applySetting("hibernate.connection.pool_size", config.persistence.pool_size + "")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("hibernate.show_sql", config.persistence.showSQL + "")
            .build();

    MetadataSources sources = new MetadataSources(registry);

    Timings.time("RegisterDBEntities", () ->
            new Reflections().getTypesAnnotatedWith(Entity.class).forEach(sources::addAnnotatedClass));

    try {
        Metadata metadata = sources.buildMetadata();
        sessionFactory = metadata.buildSessionFactory();
    } catch (Exception e) {
        StandardServiceRegistryBuilder.destroy(registry);
        e.printStackTrace();
    }
}
 
Example 10
Project: springJpaKata   File: ORMStandaloneTestCase.java   View source code 6 votes vote down vote up
@Before
public void setup() {
	StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
		.applySetting( "hibernate.show_sql", "true" )
		.applySetting( "hibernate.format_sql", "true" )
		.applySetting( "hibernate.hbm2ddl.auto", "update" )
		.applySetting( "hibernate.dialect", "org.hibernate.dialect.H2Dialect" )
		.applySetting( "hibernate.connection.driver_class", "org.h2.Driver" )
		.applySetting( "hibernate.connection.url", "jdbc:h2:mem:testdbHibernate" )
		.applySetting( "hibernate.connection.username", "sa" )
		.applySetting( "hibernate.connection.password", "" )
		.applySetting( "hibernate.use_sql_comment", "true" )
		;
	Metadata metadata  = null;
	if(packageBase()== null){
	metadata= new MetadataSources( srb.build() ).addAnnotatedClass(getEntityClass()).buildMetadata();
	}else{
	    metadata= new MetadataSources( srb.build() )
	            .addAnnotatedClass(Item.class)
	            .addAnnotatedClass(Offer.class)

	            .addPackage(packageBase()).buildMetadata();
	}

       sf = metadata.buildSessionFactory();
   }
 
Example 11
Project: springJpaKata   File: ORMStandaloneClassTestCase.java   View source code 6 votes vote down vote up
@BeforeClass
public static void setup() {
    // @formatter:off
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.show_sql", "true")
            .applySetting("hibernate.format_sql", "true")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("use_sql_comments", "true")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
            .applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate")
            .applySetting("hibernate.connection.username", "sa")
            .applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(EmailMessage.class).addAnnotatedClass(Email.class).buildMetadata();

    sf = metadata.buildSessionFactory();
    // @formatter:on
}
 
Example 12
Project: springJpaKata   File: ORMStandaloneClassTestCase.java   View source code 6 votes vote down vote up
@BeforeClass
public static void setup() {
    // @formatter:off
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.show_sql", "true")
            .applySetting("hibernate.format_sql", "true")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("use_sql_comments", "true")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
            .applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate")
            .applySetting("hibernate.connection.username", "sa")
            .applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(Address.class).addAnnotatedClass(User.class).buildMetadata();

    sf = metadata.buildSessionFactory();
    // @formatter:on
}
 
Example 13
Project: springJpaKata   File: ORMStandaloneClassTestCase.java   View source code 6 votes vote down vote up
@BeforeClass
public static void setup() {
    // @formatter:off
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.show_sql", "true")
            .applySetting("hibernate.format_sql", "true")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("use_sql_comments", "true")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
            .applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate")
            .applySetting("hibernate.connection.username", "sa")
            .applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(Address.class).addAnnotatedClass(User.class).buildMetadata();

    sf = metadata.buildSessionFactory();
    // @formatter:on
}
 
Example 14
Project: springJpaKata   File: ORMStandaloneClassTestCase.java   View source code 6 votes vote down vote up
@BeforeClass
public static void setup() {
    // @formatter:off
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.show_sql", "true")
            .applySetting("hibernate.format_sql", "true")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("use_sql_comments", "true")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
            .applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate")
            .applySetting("hibernate.connection.username", "sa")
            .applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(EmailMessage.class).addAnnotatedClass(Email.class).buildMetadata();

    sf = metadata.buildSessionFactory();
    // @formatter:on
}
 
Example 15
Project: springJpaKata   File: ORMStandaloneClassTestCase.java   View source code 6 votes vote down vote up
@BeforeClass
public static void setup() {
    // @formatter:off
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
            .applySetting("hibernate.show_sql", "true")
            .applySetting("hibernate.format_sql", "true")
            .applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("use_sql_comments", "true")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect")
            .applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate")
            .applySetting("hibernate.connection.username", "sa")
            .applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(EmailMessage.class).addAnnotatedClass(Email.class).buildMetadata();

    sf = metadata.buildSessionFactory();
    // @formatter:on
}
 
Example 16
Project: springJpaKata   File: ORMStandaloneTestCase.java   View source code 6 votes vote down vote up
@Before
public void setup() {
	StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
		.applySetting( "hibernate.show_sql", "true" )
		.applySetting( "hibernate.format_sql", "true" )
		.applySetting( "hibernate.hbm2ddl.auto", "update" )
		.applySetting( "hibernate.dialect", "org.hibernate.dialect.H2Dialect" )
		.applySetting( "hibernate.connection.driver_class", "org.h2.Driver" )
		.applySetting( "hibernate.connection.url", "jdbc:h2:mem:testdbHibernate" )
		.applySetting( "hibernate.connection.username", "sa" )
		.applySetting( "hibernate.connection.password", "" )
		.applySetting( "hibernate.use_sql_comment", "true" )
		;
	Metadata metadata  = null;
	if(packageBase()== null){
	metadata= new MetadataSources( srb.build() ).addAnnotatedClass(getEntityClass()).buildMetadata();
	}else{
	    metadata= new MetadataSources( srb.build() )
	            .addAnnotatedClass(Item.class)
	            .addAnnotatedClass(Offer.class)

	            .addPackage(packageBase()).buildMetadata();
	}

       sf = metadata.buildSessionFactory();
   }
 
Example 17
Project: high-performance-java-persistence   File: MetadataTest.java   View source code 6 votes vote down vote up
@Test
public void testEntityToDatabaseBindingMetadata() {
    Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();

    for ( PersistentClass persistentClass : metadata.getEntityBindings()) {
        Table table = persistentClass.getTable();
        LOGGER.info( "Entity: {} is mapped to table: {}",
                     persistentClass.getClassName(),
                     table.getName()
        );

        for(Iterator propertyIterator =
                persistentClass.getPropertyIterator(); propertyIterator.hasNext(); ) {
            Property property = (Property) propertyIterator.next();
            for(Iterator columnIterator =
                    property.getColumnIterator(); columnIterator.hasNext(); ) {
                Column column = (Column) columnIterator.next();
                LOGGER.info( "Property: {} is mapped on table column: {} of type: {}",
                             property.getName(),
                             column.getName(),
                             column.getSqlType()
                );
            }
        }
    }
}
 
Example 18
Project: juddi   File: App.java   View source code 6 votes vote down vote up
/**
 * Method that actually creates the file.
 *
 * @param dbDialect to use
 */
private void generate(Dialect dialect) {

        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
        ssrb.applySetting("hibernate.dialect", dialect.getDialectClass());
        StandardServiceRegistry standardServiceRegistry = ssrb.build();

        MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
        for (Class clzz : jpaClasses) {
                metadataSources.addAnnotatedClass(clzz);
        }

        Metadata metadata = metadataSources.buildMetadata();

        SchemaExport export = new SchemaExport();

        export.setDelimiter(";");
        export.setOutputFile(dialect.name().toLowerCase() + ".ddl");
        //export.execute(true, false, false, true);
        export.execute(EnumSet.of(TargetType.SCRIPT), Action.BOTH, metadata);
}
 
Example 19
Project: jooby   File: HbmTest.java   View source code 6 votes vote down vote up
private Block metadataBuilder() {
  return unit -> {
    MetadataBuilder mb = unit.get(MetadataBuilder.class);
    expect(mb.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE))
        .andReturn(mb);
    expect(mb.applyScanEnvironment(unit.get(ScanEnvironment.class))).andReturn(mb);

    SessionFactoryBuilder sfb = unit.mock(SessionFactoryBuilder.class);
    unit.registerMock(SessionFactoryBuilder.class, sfb);

    Metadata md = unit.mock(Metadata.class);
    expect(md.getSessionFactoryBuilder()).andReturn(sfb);

    expect(mb.build()).andReturn(md);

    unit.registerMock(Metadata.class, md);
  };
}
 
Example 20
Project: otus_java_2017_06   File: DBServiceImpl.java   View source code 5 votes vote down vote up
public DBServiceImpl() {
    StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();

    Map<String, Object> settings = new HashMap<>();
    settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
    settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
    settings.put(Environment.URL, "jdbc:mysql://localhost:3306/db_example");
    settings.put(Environment.USER, "tully");
    settings.put(Environment.PASS, "tully");
    settings.put(Environment.HBM2DDL_AUTO, "create");
    settings.put(Environment.SHOW_SQL, true);
    settings.put(Environment.ENABLE_LAZY_LOAD_NO_TRANS, true);

    // c3p0 configuration
    settings.put(Environment.C3P0_MIN_SIZE, 5);         //Minimum size of pool
    settings.put(Environment.C3P0_MAX_SIZE, 20);        //Maximum size of pool
    settings.put(Environment.C3P0_ACQUIRE_INCREMENT, 1);//Number of connections acquired at a time when pool is exhausted
    settings.put(Environment.C3P0_TIMEOUT, 1800);       //Connection idle time

    registryBuilder.applySettings(settings);

    ServiceRegistry registry = registryBuilder.build();
    MetadataSources sources = new MetadataSources(registry)
            .addAnnotatedClass(PhoneDataSet.class)
            .addAnnotatedClass(UserDataSet.class)
            .addAnnotatedClass(AddressDataSet.class);


    Metadata metadata = sources.getMetadataBuilder().build();
    sessionFactory = metadata.getSessionFactoryBuilder().build();
}
 
Example 21
Project: spanner-hibernate   File: CloudSpannerUniqueDelegate.java   View source code 5 votes vote down vote up
@Override
public String getAlterTableToAddUniqueKeyCommand(UniqueKey uniqueKey, Metadata metadata)
{
	ConfigurationService config = metadata.getDatabase().getBuildingOptions().getServiceRegistry()
			.getService(ConfigurationService.class);
	if (config != null)
	{
		String value = config.getSetting("hibernate.hbm2ddl.auto", StandardConverters.STRING);
		if (!value.equalsIgnoreCase("update"))
		{
			// We should only check whether it is already present in an
			// update scenario, in all other scenarios, just return the
			// actual create statement.
			return org.hibernate.mapping.Index.buildSqlCreateIndexString(dialect, uniqueKey.getName(),
					uniqueKey.getTable(), uniqueKey.columnIterator(), uniqueKey.getColumnOrderMap(), true,
					metadata);
		}
	}
	// First check that this unique key is not already present, as this is a
	// lot faster than trying to create it and then fail.
	initIndices();
	UniqueIndex idx = indices.getIndex(uniqueKey);
	if (idx != null)
	{
		return null;
	}
	return org.hibernate.mapping.Index.buildSqlCreateIndexString(dialect, uniqueKey.getName(), uniqueKey.getTable(),
			uniqueKey.columnIterator(), uniqueKey.getColumnOrderMap(), true, metadata);
}
 
Example 22
Project: spanner-hibernate   File: CloudSpannerSchemaHandler.java   View source code 5 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
	for (Object o : args)
	{
		if (o instanceof Metadata)
		{
			addAuxiliaryDatabaseObjects(((Metadata) o).getDatabase());
			break;
		}
	}
	return method.invoke(delegate, args);
}
 
Example 23
Project: JavaEE   File: App.java   View source code 5 votes vote down vote up
/**
 * Creating a session
 * @return org.hibernate.Session
 */
private Session createHibernateSession() {
    try {
        Map<String, String> settings = new HashMap<String, String>();
        settings.put("hibernate.connection.driver_class", "org.sqlite.JDBC");
        settings.put("hibernate.connection.url", "jdbc:sqlite:mysqlite.db");
        settings.put("hibernate.connection.username", "");
        settings.put("hibernate.connection.password", "");
        settings.put("hibernate.show_sql", "true");
        settings.put("hibernate.hbm2ddl.auto", "update");

        StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .applySettings(settings)
                .build();

        MetadataSources sources = new MetadataSources(registry)
                .addAnnotatedClass(Person.class);

        Metadata metadata = sources
                .getMetadataBuilder()
                .build();

        SessionFactory sessionFactory = metadata
                .getSessionFactoryBuilder()
                .build();

        session = sessionFactory.openSession();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        return null;
    }
    System.out.println("Session created successfully.");
    return session;
}
 
Example 24
Project: gitplex-mit   File: DefaultPersistManager.java   View source code 5 votes vote down vote up
protected Metadata buildMetadata() {
	MetadataSources metadataSources = new MetadataSources(serviceRegistry);
	for (Class<? extends AbstractEntity> each: LoaderUtils.findImplementations(AbstractEntity.class, AbstractEntity.class)) {
		metadataSources.addAnnotatedClass(each);
	}
	
	return metadataSources.getMetadataBuilder().applyPhysicalNamingStrategy(physicalNamingStrategy).build();
}
 
Example 25
Project: gitplex-mit   File: DefaultPersistManager.java   View source code 5 votes vote down vote up
@Sessional
@Override
public void importData(Metadata metadata, File dataDir) {
	Session session = dao.getSession();
	List<Class<?>> entityTypes = getEntityTypes(sessionFactory);
	Collections.reverse(entityTypes);
	for (Class<?> entityType: entityTypes) {
		File[] dataFiles = dataDir.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				return name.startsWith(entityType.getSimpleName() + "s.xml");
			}
			
		});
		for (File file: dataFiles) {
			try {
				logger.info("Importing from data file '" + file.getName() + "'...");
				session.beginTransaction();
				VersionedDocument dom = VersionedDocument.fromFile(file);
				
				for (Element element: dom.getRootElement().elements()) {
					element.detach();
					AbstractEntity entity = (AbstractEntity) new VersionedDocument(DocumentHelper.createDocument(element)).toBean();
					session.replicate(entity, ReplicationMode.EXCEPTION);
				}
				session.flush();
				session.clear();
				session.getTransaction().commit();
			} catch (Throwable e) {
				session.getTransaction().rollback();
				throw Throwables.propagate(e);
			}
		}
	}	
}
 
Example 26
Project: gitplex-mit   File: DefaultPersistManager.java   View source code 5 votes vote down vote up
protected void validateData(Metadata metadata, File dataDir) {
	List<Class<?>> entityTypes = getEntityTypes(sessionFactory);
	Collections.reverse(entityTypes);
	for (Class<?> entityType: entityTypes) {
		File[] dataFiles = dataDir.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				return name.startsWith(entityType.getSimpleName() + "s.xml");
			}
			
		});
		for (File file: dataFiles) {
			try {
				logger.info("Validating data file '" + file.getName() + "'...");
				VersionedDocument dom = VersionedDocument.fromFile(file);
				
				for (Element element: dom.getRootElement().elements()) {
					element.detach();
					AbstractEntity entity = (AbstractEntity) new VersionedDocument(DocumentHelper.createDocument(element)).toBean();
					validator.validate(entity);
				}
			} catch (Throwable e) {
				throw Throwables.propagate(e);
			}
		}
	}	
}
 
Example 27
Project: gitplex-mit   File: ResetAdminPasswordCommand.java   View source code 5 votes vote down vote up
@Override
public void start() {
	if (Bootstrap.command.getArgs().length == 0) {
		logger.error("Missing password parameter. Usage: {} <new password>", Bootstrap.command.getScript());
		System.exit(1);
	}
	if (Bootstrap.isServerRunning(Bootstrap.installDir)) {
		logger.error("Please stop server before resetting admin password");
		System.exit(1);
	}

	checkDataVersion(false);

	Metadata metadata = buildMetadata();
	sessionFactory = metadata.getSessionFactoryBuilder().applyInterceptor(interceptor).build();
	
	User root = userManager.get(User.ROOT_ID);
	if (root == null) {
		logger.error("Server not set up yet");
		System.exit(1);
	}
	String password = Bootstrap.command.getArgs()[0];
	root.setPassword(passwordService.encryptPassword(password));
	userManager.save(root);
	
	// wait for a short period to have embedded db flushing data
	try {
		Thread.sleep(1000);
	} catch (InterruptedException e) {
		throw new RuntimeException(e);
	}
	sessionFactory.close();
	
	logger.info("Password of user '" + root.getName() + "' has been reset to: " + password);
	System.exit(0);
}
 
Example 28
Project: gitplex-mit   File: RestoreDBCommand.java   View source code 5 votes vote down vote up
private void doRestore(Metadata metadata, File dataDir) {
	migrateData(dataDir);
	validateData(metadata, dataDir);

	String dbDataVersion = checkDataVersion(true);

	if (dbDataVersion != null) {
		logger.info("Cleaning database...");
		cleanDatabase(metadata);
	}
	
	logger.info("Creating tables...");
	createTables(metadata);
	
	logger.info("Importing data into database...");
	importData(metadata, dataDir);
	
	logger.info("Applying foreign key constraints...");
	try {
		applyConstraints(metadata);		
	} catch (Exception e) {
		logger.error("Failed to apply database constraints", e);
		logger.info("If above error is caused by foreign key constraint violations, you may fix it via your database sql tool, "
				+ "and then run {} to reapply database constraints", Command.getScript("apply_db_constraints"));
		System.exit(1);
	}
}
 
Example 29
Project: otus_java_2017_04   File: DBServiceImpl.java   View source code 5 votes vote down vote up
public DBServiceImpl() {
    StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();

    Map<String, Object> settings = new HashMap<>();
    settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
    settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
    settings.put(Environment.URL, "jdbc:mysql://localhost:3306/db_example");
    settings.put(Environment.USER, "tully");
    settings.put(Environment.PASS, "tully");
    settings.put(Environment.HBM2DDL_AUTO, "create");
    settings.put(Environment.SHOW_SQL, true);
    settings.put(Environment.ENABLE_LAZY_LOAD_NO_TRANS, true);

    // c3p0 configuration
    settings.put(Environment.C3P0_MIN_SIZE, 5);         //Minimum size of pool
    settings.put(Environment.C3P0_MAX_SIZE, 20);        //Maximum size of pool
    settings.put(Environment.C3P0_ACQUIRE_INCREMENT, 1);//Number of connections acquired at a time when pool is exhausted
    settings.put(Environment.C3P0_TIMEOUT, 1800);       //Connection idle time

    registryBuilder.applySettings(settings);

    ServiceRegistry registry = registryBuilder.build();
    MetadataSources sources = new MetadataSources(registry)
            .addAnnotatedClass(PhoneDataSet.class)
            .addAnnotatedClass(UserDataSet.class);


    Metadata metadata = sources.getMetadataBuilder().build();
    sessionFactory = metadata.getSessionFactoryBuilder().build();
}
 
Example 30
Project: hibernateMaster   File: SingleFactoryEngine.java   View source code 5 votes vote down vote up
@Override
	public SessionFactory buildFactory(String configFile) {
		try {
			//configuration = new Configuration().configure(configFile);
//			StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
//			.applySettings(configuration.getProperties());
//			SessionFactory factory2 = configuration.buildSessionFactory(builder.build());
			
			
			StandardServiceRegistry standardRegistry = new   StandardServiceRegistryBuilder()
				    .configure(configFile)
				    .build();

			MetadataSources metadataSources = new MetadataSources( standardRegistry );
			
			DomainScanner instanceFromProperties = getScanner(configFile);
			List<Class<? extends BaseDatabaseDomain>> scan = instanceFromProperties.scan(configFile);
			for(Class<? extends BaseDatabaseDomain> temp:scan){
				metadataSources.addAnnotatedClass(temp);
			}
			
		//	new HibernateUtil().scanDomain(metadataSources);
			
			Metadata metadata = metadataSources.getMetadataBuilder()
			    .applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
			    .build();

			SessionFactory factory2 = metadata.getSessionFactoryBuilder().build();
		
			
			return factory2;
			/*ProxoolConnectionProvider aConnectionProvider;*/
		} catch (Exception e) {
			steed.util.logging.LoggerFactory.getLogger().error("创建sessionFactory失败",e);
		}
		return null;
	}
 
Example 31
Project: Projeto-Flash   File: HibernateUtil.java   View source code 5 votes vote down vote up
private static SessionFactory createSessionFactory() {
    standardRegistry = new StandardServiceRegistryBuilder()
            .configure( "hibernate.cfg.xml" )
            .build();

    Metadata metadata = new MetadataSources( standardRegistry )
            .getMetadataBuilder()
            .build();

    sessionFactory = metadata.getSessionFactoryBuilder().build();

    return sessionFactory;
}
 
Example 32
Project: springJpaKata   File: ORMStandaloneClassTestCase.java   View source code 5 votes vote down vote up
@BeforeClass
public static void setup() {
    StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder().applySetting("hibernate.show_sql", "true").applySetting("hibernate.format_sql", "true").applySetting("hibernate.hbm2ddl.auto", "update")
            .applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect").applySetting("hibernate.connection.driver_class", "org.h2.Driver")
            .applySetting("hibernate.connection.url", "jdbc:h2:mem:testdbHibernate").applySetting("hibernate.connection.username", "sa").applySetting("hibernate.connection.password", "")
            .applySetting("hibernate.use_sql_comment", "true");
    Metadata metadata = null;
    log.info("+++ setup");
    metadata = new MetadataSources(srb.build()).addAnnotatedClass(Book.class).buildMetadata();

    sf = metadata.buildSessionFactory();
}
 
Example 33
Project: springJpaKata   File: ORMStandaloneTestCase.java   View source code 5 votes vote down vote up
@Before
public void setup() {
	StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
		.applySetting( "hibernate.show_sql", "true" )
		.applySetting( "hibernate.format_sql", "true" )
		.applySetting( "hibernate.hbm2ddl.auto", "update" )
		.applySetting( "hibernate.dialect", "org.hibernate.dialect.H2Dialect" )
		.applySetting( "hibernate.connection.driver_class", "org.h2.Driver" )
		.applySetting( "hibernate.connection.url", "jdbc:h2:mem:testdbHibernate" )
		.applySetting( "hibernate.connection.username", "sa" )
		.applySetting( "hibernate.connection.password", "" )
		.applySetting( "hibernate.use_sql_comment", "true" )
		;
	Metadata metadata  = null;
	if(packageBase()== null){
	metadata= new MetadataSources( srb.build() ).addAnnotatedClass(getEntityClass()).buildMetadata();
	}else{
	    metadata= new MetadataSources( srb.build() )
	            .addAnnotatedClass(Item.class)
	            .addAnnotatedClass(Tank.class)
	            .addAnnotatedClass(Crew.class)
	            .addAnnotatedClass(TankBi.class)
	            .addAnnotatedClass(CrewBi.class)
	            .addPackage(packageBase()).buildMetadata();
	}

       sf = metadata.buildSessionFactory();
   }
 
Example 34
Project: springJpaKata   File: ORMStandaloneMany2OneTestCase.java   View source code 5 votes vote down vote up
@Before
public void setup() {
	StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder()
		.applySetting( "hibernate.show_sql", "true" )
		.applySetting( "hibernate.format_sql", "true" )
		.applySetting( "hibernate.hbm2ddl.auto", "update" )
		.applySetting( "hibernate.dialect", "org.hibernate.dialect.H2Dialect" )
		.applySetting( "hibernate.connection.driver_class", "org.h2.Driver" )
		.applySetting( "hibernate.connection.url", "jdbc:h2:mem:testdbHibernate" )
		.applySetting( "hibernate.connection.username", "sa" )
		.applySetting( "hibernate.connection.password", "" )
		.applySetting( "hibernate.use_sql_comment", "true" )
		;
	Metadata metadata  = null;
	if(packageBase()== null){
	metadata= new MetadataSources( srb.build() ).addAnnotatedClass(getEntityClass()).buildMetadata();
	}else{
	    metadata= new MetadataSources( srb.build() )
	            .addAnnotatedClass(Product.class)
	            .addAnnotatedClass(ProductCustomer.class)
	            .addAnnotatedClass(ProductResource.class)
	            .addAnnotatedClass(Part.class)

	            .addPackage(packageBase()).buildMetadata();
	}

       sf = metadata.buildSessionFactory();
   }
 
Example 35
Project: tiramisu   File: HibernateUtil.java   View source code 5 votes vote down vote up
/**
 * Method to build the hibernate session factory.
 * 
 * @return A Hibernate SessionFactory object.
 */
private static synchronized SessionFactory buildSessionFactory() {
	try {
		if (HibernateUtil.serviceRegistry == null) {
			HibernateUtil.serviceRegistry = new StandardServiceRegistryBuilder()
					.configure("au/com/ifti/models/hibernate/database.xml").build();
		}
		Metadata metadata = new MetadataSources(HibernateUtil.serviceRegistry).getMetadataBuilder().build();
		return metadata.getSessionFactoryBuilder().build();
	} catch (Throwable ex) {
		throw new ExceptionInInitializerError(ex);
	}
}
 
Example 36
Project: dhis2-core   File: DeletedObjectIntegrator.java   View source code 5 votes vote down vote up
@Override
public void integrate( Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry )
{
    final EventListenerRegistry registry = serviceRegistry.getService( EventListenerRegistry.class );

    DeletedObjectPostDeleteEventListener listener = new DeletedObjectPostDeleteEventListener();
    registry.appendListeners( EventType.POST_DELETE, listener );
}
 
Example 37
Project: elide   File: Util.java   View source code 5 votes vote down vote up
/**
 * Retrieve a hibernate session factory.
 *
 * @param hibernate5ConfigPath File path to hibernate config (i.e. hibernate-cfg.xml)
 * @param modelPackageName Name of package containing all models to be loaded by hibernate
 * @return Hibernate session factory.
 */
public static SessionFactory getSessionFactory(String hibernate5ConfigPath, String modelPackageName) {
    StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
            .configure(new File(hibernate5ConfigPath))
            .build();
    MetadataSources sources = new MetadataSources(standardRegistry);

    getAllEntities(modelPackageName).forEach(sources::addAnnotatedClass);

    Metadata metaData =  sources.getMetadataBuilder().build();
    return metaData.getSessionFactoryBuilder().build();
}
 
Example 38
Project: ignite   File: HibernateL2CacheStrategySelfTest.java   View source code 5 votes vote down vote up
/**
 * @param accessType Cache access typr.
 * @param igniteInstanceName Name of the grid providing caches.
 * @return Session factory.
 */
private SessionFactory startHibernate(AccessType accessType, String igniteInstanceName) {
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

    builder.applySetting("hibernate.connection.url", CONNECTION_URL);

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

    builder.applySetting(USE_STRUCTURED_CACHE, "true");
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY1_NAME, "cache1");
    builder.applySetting(REGION_CACHE_PROPERTY + ENTITY2_NAME, "cache2");
    builder.applySetting(REGION_CACHE_PROPERTY + TIMESTAMP_CACHE, TIMESTAMP_CACHE);
    builder.applySetting(REGION_CACHE_PROPERTY + QUERY_CACHE, QUERY_CACHE);

    MetadataSources metadataSources = new MetadataSources(builder.build());

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

    Metadata metadata = metadataSources.buildMetadata();

    for (PersistentClass entityBinding : metadata.getEntityBindings()) {
        if (!entityBinding.isInherited())
            ((RootClass)entityBinding).setCacheConcurrencyStrategy(accessType.getExternalName());
    }

    return metadata.buildSessionFactory();
}
 
Example 39
Project: ignite   File: HibernateL2CacheSelfTest.java   View source code 5 votes vote down vote up
/**
 * Starts Hibernate.
 *
 * @param accessType Cache access type.
 * @param igniteInstanceName Ignite instance name.
 * @return Session factory.
 */
private SessionFactory startHibernate(org.hibernate.cache.spi.access.AccessType accessType, String igniteInstanceName) {
    StandardServiceRegistryBuilder builder = registryBuilder();

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

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

    StandardServiceRegistry srvcRegistry = builder.build();

    MetadataSources metadataSources = new MetadataSources(srvcRegistry);

    for (Class entityClass : getAnnotatedClasses())
        metadataSources.addAnnotatedClass(entityClass);

    Metadata metadata = metadataSources.buildMetadata();

    for (PersistentClass entityBinding : metadata.getEntityBindings()) {
        if (!entityBinding.isInherited())
            ((RootClass)entityBinding).setCacheConcurrencyStrategy(accessType.getExternalName());
    }

    for (org.hibernate.mapping.Collection collectionBinding : metadata.getCollectionBindings())
        collectionBinding.setCacheConcurrencyStrategy(accessType.getExternalName() );

    return metadata.buildSessionFactory();
}
 
Example 40
Project: high-performance-java-persistence   File: OptimisticLockingChildUpdatesRootVersionTest.java   View source code 5 votes vote down vote up
@Override
public void integrate(
        Metadata metadata,
        SessionFactoryImplementor sessionFactory,
        SessionFactoryServiceRegistry serviceRegistry) {

    final EventListenerRegistry eventListenerRegistry =
            serviceRegistry.getService( EventListenerRegistry.class );

    eventListenerRegistry.appendListeners(EventType.PERSIST, RootAwareInsertEventListener.INSTANCE);
    eventListenerRegistry.appendListeners(EventType.FLUSH_ENTITY, RootAwareUpdateAndDeleteEventListener.INSTANCE);
}