org.hibernate.boot.MetadataSources Java Examples
The following examples show how to use
org.hibernate.boot.MetadataSources.
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 File: App.java From juddi with Apache License 2.0 | 6 votes |
/** * 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 #2
Source File: LocalSessionFactoryBean.java From java-technology-stack with MIT License | 6 votes |
/** * Determine the Hibernate {@link MetadataSources} to use. * <p>Can also be externally called to initialize and pre-populate a {@link MetadataSources} * instance which is then going to be used for {@link SessionFactory} building. * @return the MetadataSources to use (never {@code null}) * @since 4.3 * @see LocalSessionFactoryBuilder#LocalSessionFactoryBuilder(DataSource, ResourceLoader, MetadataSources) */ public MetadataSources getMetadataSources() { this.metadataSourcesAccessed = true; if (this.metadataSources == null) { BootstrapServiceRegistryBuilder builder = new BootstrapServiceRegistryBuilder(); if (this.resourcePatternResolver != null) { builder = builder.applyClassLoader(this.resourcePatternResolver.getClassLoader()); } if (this.hibernateIntegrators != null) { for (Integrator integrator : this.hibernateIntegrators) { builder = builder.applyIntegrator(integrator); } } this.metadataSources = new MetadataSources(builder.build()); } return this.metadataSources; }
Example #3
Source File: TestDal.java From Insights with Apache License 2.0 | 6 votes |
public static void main(String[] args) { /*Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); configuration.setProperty("hibernate.connection.username","grafana123"); ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).configure().build();*/ ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build(); MetadataSources sources = new MetadataSources( standardRegistry ); sources.addAnnotatedClass( Test.class ); Metadata metadata = sources.getMetadataBuilder().applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE).build(); SessionFactory sessionFactory = metadata.buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Test s = new Test(); s.setName("12Vishal123"); session.save(s); session.getTransaction().commit(); session.close(); sessionFactory.close(); }
Example #4
Source File: MappingReference.java From lams with GNU General Public License v2.0 | 6 votes |
public void apply(MetadataSources metadataSources) { switch ( getType() ) { case RESOURCE: { metadataSources.addResource( getReference() ); break; } case CLASS: { metadataSources.addAnnotatedClassName( getReference() ); break; } case FILE: { metadataSources.addFile( getReference() ); break; } case PACKAGE: { metadataSources.addPackage( getReference() ); break; } case JAR: { metadataSources.addJar( new File( getReference() ) ); break; } } }
Example #5
Source File: NamingStrategyLiveTest.java From tutorials with MIT License | 6 votes |
@Before public void init() { try { Configuration configuration = new Configuration(); Properties properties = new Properties(); properties.load(Thread.currentThread() .getContextClassLoader() .getResourceAsStream("hibernate-namingstrategy.properties")); configuration.setProperties(properties); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) .build(); MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addAnnotatedClass(Customer.class); SessionFactory factory = metadataSources.buildMetadata() .buildSessionFactory(); session = factory.openSession(); } catch (HibernateException | IOException e) { fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); } }
Example #6
Source File: BootstrapAPIIntegrationTest.java From tutorials with MIT License | 6 votes |
@Test public void whenServiceRegistryAndMetadata_thenSessionFactory() throws IOException { BootstrapServiceRegistry bootstrapRegistry = new BootstrapServiceRegistryBuilder() .build(); ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder(bootstrapRegistry) // No need for hibernate.cfg.xml file, an hibernate.properties is sufficient. //.configure() .build(); MetadataSources metadataSources = new MetadataSources(standardRegistry); metadataSources.addAnnotatedClass(Movie.class); Metadata metadata = metadataSources.getMetadataBuilder().build(); sessionFactory = metadata.buildSessionFactory(); assertNotNull(sessionFactory); sessionFactory.close(); }
Example #7
Source File: App.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
/** * The main method that does the CRUD operations. */ public static void main(String[] args) { // create a Hibernate sessionFactory and session StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build(); SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata() .buildSessionFactory(); Session session = sessionFactory.openSession(); clearData(session); writeData(session); readData(session); // close Hibernate session and sessionFactory session.close(); sessionFactory.close(); }
Example #8
Source File: HibernateLoggingIntegrationTest.java From tutorials with MIT License | 6 votes |
@Before public void setUp() throws IOException { final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate-logging.cfg.xml") .build(); try { sessionFactory = new MetadataSources(registry).buildMetadata() .buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(new Employee("John Smith", "001")); session.getTransaction() .commit(); session.close(); } catch (Exception e) { fail(e); StandardServiceRegistryBuilder.destroy(registry); } }
Example #9
Source File: GeneratedSelectStatementsTests.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
/** * Set up the metadata for Hibernate to generate schema statements. */ @Before public void setup() throws SQLException { this.jdbcMockObjectFactory = new JDBCMockObjectFactory(); this.jdbcMockObjectFactory.registerMockDriver(); MockConnection connection = this.jdbcMockObjectFactory.getMockConnection(); connection.setMetaData(MockJdbcUtils.metaDataBuilder().build()); this.jdbcMockObjectFactory.getMockDriver() .setupConnection(connection); this.registry = new StandardServiceRegistryBuilder() .applySetting("hibernate.dialect", SpannerDialect.class.getName()) // must NOT set a driver class name so that Hibernate will use java.sql.DriverManager // and discover the only mock driver we have set up. .applySetting("hibernate.connection.url", "unused") .applySetting("hibernate.connection.username", "unused") .applySetting("hibernate.connection.password", "unused") .applySetting("hibernate.hbm2ddl.auto", "create") .build(); this.metadata = new MetadataSources(this.registry).addAnnotatedClass(TestEntity.class) .addAnnotatedClass(SubTestEntity.class).buildMetadata(); }
Example #10
Source File: SpannerTableExporterTests.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void generateCreateStringsNoPkEntityTest() { assertThatThrownBy(() -> { Metadata metadata = new MetadataSources(this.registry) .addAnnotatedClass(NoPkEntity.class) .buildMetadata(); new SchemaExport() .setOutputFile("unused") .createOnly(EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT), metadata); }) .isInstanceOf(AnnotationException.class) .hasMessage( "No identifier specified for entity: " + "com.google.cloud.spanner.hibernate.SpannerTableExporterTests$NoPkEntity"); }
Example #11
Source File: TestHibernateBootstrapping.java From HibernateTips with MIT License | 6 votes |
@Test public void bootstrapping() { log.info("... bootstrapping ..."); ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build(); SessionFactory sessionFactory = new MetadataSources(standardRegistry) .addAnnotatedClass(Author.class).buildMetadata() .buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); Author a = new Author(); a.setFirstName("Thorben"); a.setLastName("Janssen"); session.persist(a); session.getTransaction().commit(); session.close(); }
Example #12
Source File: SpannerTableExporterTests.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void generateDeleteStringsWithIndices() throws IOException, SQLException { this.connection.setMetaData(MockJdbcUtils.metaDataBuilder() .setTables("Employee", "hibernate_sequence") .setIndices("name_index") .build()); Metadata employeeMetadata = new MetadataSources(this.registry).addAnnotatedClass(Employee.class).buildMetadata(); String testFileName = UUID.randomUUID().toString(); new SchemaExport().setOutputFile(testFileName) .drop(EnumSet.of(TargetType.STDOUT, TargetType.SCRIPT), employeeMetadata); File scriptFile = new File(testFileName); scriptFile.deleteOnExit(); List<String> statements = Files.readAllLines(scriptFile.toPath()); assertThat(statements).containsExactly( "START BATCH DDL", "drop index name_index", "drop table Employee", "drop table hibernate_sequence", "RUN BATCH"); }
Example #13
Source File: SpannerTableExporterTests.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
/** * Set up the metadata for Hibernate to generate schema statements. */ @Before public void setup() throws SQLException { JDBCMockObjectFactory jdbcMockObjectFactory = new JDBCMockObjectFactory(); jdbcMockObjectFactory.registerMockDriver(); this.connection = jdbcMockObjectFactory.getMockConnection(); this.connection.setMetaData(MockJdbcUtils.metaDataBuilder().build()); jdbcMockObjectFactory.getMockDriver().setupConnection(this.connection); this.registry = new StandardServiceRegistryBuilder() .applySetting("hibernate.dialect", SpannerDialect.class.getName()) .applySetting("hibernate.connection.url", "unused") .build(); this.metadata = new MetadataSources(this.registry).addAnnotatedClass(TestEntity.class).buildMetadata(); }
Example #14
Source File: GeneratedCreateTableStatementsTests.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void testCreateUniqueIndexes_uniqueColumn() throws SQLException { Metadata metadata = new MetadataSources(this.registry) .addAnnotatedClass(Airplane.class) .buildMetadata(); Session session = metadata.buildSessionFactory().openSession(); session.beginTransaction(); session.close(); List<String> sqlStrings = this.connection.getStatementResultSetHandler().getExecutedStatements(); assertThat(sqlStrings).containsExactly( "START BATCH DDL", "RUN BATCH", "START BATCH DDL", "create table Airplane (id STRING(255) not null,modelName STRING(255)) PRIMARY KEY (id)", "create unique index UK_gc568wb30sampsuirwne5jqgh on Airplane (modelName)", "RUN BATCH" ); }
Example #15
Source File: HibernateSampleApplication.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** * Main method that runs a simple console application that saves a {@link Person} entity and then * retrieves it to print to the console. */ public static void main(String[] args) { // Create Hibernate environment objects. StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure() .build(); SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata() .buildSessionFactory(); Session session = sessionFactory.openSession(); // Save an entity into Spanner Table. savePerson(session); session.close(); }
Example #16
Source File: HibernateUtil.java From tutorials with MIT License | 6 votes |
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.pojo"); metadataSources.addAnnotatedClass(com.baeldung.hibernate.joincolumn.OfficialEmployee.class); metadataSources.addAnnotatedClass(Email.class); metadataSources.addAnnotatedClass(Office.class); metadataSources.addAnnotatedClass(OfficeAddress.class); Metadata metadata = metadataSources.getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder() .build(); }
Example #17
Source File: HibernateUtil.java From tutorials with MIT License | 6 votes |
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.pojo"); metadataSources.addAnnotatedClass(Student.class); metadataSources.addAnnotatedClass(DeptEmployee.class); metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class); Metadata metadata = metadataSources.getMetadataBuilder() .applyBasicType(LocalDateStringType.INSTANCE) .build(); return metadata.getSessionFactoryBuilder() .build(); }
Example #18
Source File: HibernateUtil.java From tutorials with MIT License | 6 votes |
private static SessionFactory buildSessionFactory(Strategy strategy) { try { ServiceRegistry serviceRegistry = configureServiceRegistry(); MetadataSources metadataSources = new MetadataSources(serviceRegistry); for (Class<?> entityClass : strategy.getEntityClasses()) { metadataSources.addAnnotatedClass(entityClass); } Metadata metadata = metadataSources.getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder() .build(); } catch (IOException ex) { throw new ExceptionInInitializerError(ex); } }
Example #19
Source File: NamedParameterUnitTest.java From tutorials with MIT License | 6 votes |
@Before public void setUp() throws Exception { final StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure() .build(); try { sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(new Event("Event 1")); session.save(new Event("Event 2")); session.getTransaction().commit(); session.close(); } catch (Exception e) { fail(e); StandardServiceRegistryBuilder.destroy(registry); } }
Example #20
Source File: HibernateUtil.java From tutorials with MIT License | 6 votes |
/** * Generates database create commands for the specified entities using Hibernate native API, SchemaExport. * Creation commands are exported into the create.sql file. */ public static void generateSchema() { Map<String, String> settings = new HashMap<>(); settings.put(Environment.URL, "jdbc:h2:mem:schema"); StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build(); MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addAnnotatedClass(Account.class); metadataSources.addAnnotatedClass(AccountSetting.class); Metadata metadata = metadataSources.buildMetadata(); SchemaExport schemaExport = new SchemaExport(); schemaExport.setFormat(true); schemaExport.setOutputFile("create.sql"); schemaExport.createOnly(EnumSet.of(TargetType.SCRIPT), metadata); }
Example #21
Source File: TransactionsTest.java From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void jdbc() { //tag::transactions-api-jdbc-example[] StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() // "jdbc" is the default, but for explicitness .applySetting( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jdbc" ) .build(); Metadata metadata = new MetadataSources( serviceRegistry ) .addAnnotatedClass( Customer.class ) .getMetadataBuilder() .build(); SessionFactory sessionFactory = metadata.getSessionFactoryBuilder() .build(); Session session = sessionFactory.openSession(); try { // calls Connection#setAutoCommit( false ) to // signal start of transaction session.getTransaction().begin(); session.createQuery( "UPDATE customer set NAME = 'Sir. '||NAME" ) .executeUpdate(); // calls Connection#commit(), if an error // happens we attempt a rollback session.getTransaction().commit(); } catch ( Exception e ) { // we may need to rollback depending on // where the exception happened if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE || session.getTransaction().getStatus() == TransactionStatus.MARKED_ROLLBACK ) { session.getTransaction().rollback(); } // handle the underlying error } finally { session.close(); sessionFactory.close(); } //end::transactions-api-jdbc-example[] }
Example #22
Source File: PersistJSONUnitTest.java From tutorials with MIT License | 6 votes |
@Before public void init() { try { Configuration configuration = new Configuration(); Properties properties = new Properties(); properties.load(Thread.currentThread() .getContextClassLoader() .getResourceAsStream("hibernate-persistjson.properties")); configuration.setProperties(properties); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) .build(); MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addAnnotatedClass(Customer.class); SessionFactory factory = metadataSources.buildMetadata() .buildSessionFactory(); session = factory.openSession(); } catch (HibernateException | IOException e) { fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]"); } }
Example #23
Source File: HibernateL2CacheSelfTest.java From ignite with Apache License 2.0 | 5 votes |
/** * 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 #24
Source File: LocalSessionFactoryBuilder.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Create a new LocalSessionFactoryBuilder for the given DataSource. * @param dataSource the JDBC DataSource that the resulting Hibernate SessionFactory should be using * (may be {@code null}) * @param resourceLoader the ResourceLoader to load application classes from * @param metadataSources the Hibernate MetadataSources service to use (e.g. reusing an existing one) * @since 4.3 */ public LocalSessionFactoryBuilder(DataSource dataSource, ResourceLoader resourceLoader, MetadataSources metadataSources) { super(metadataSources); getProperties().put(AvailableSettings.CURRENT_SESSION_CONTEXT_CLASS, SpringSessionContext.class.getName()); if (dataSource != null) { getProperties().put(AvailableSettings.DATASOURCE, dataSource); } // Hibernate 5.1/5.2: manually enforce connection release mode ON_CLOSE (the former default) try { // Try Hibernate 5.2 AvailableSettings.class.getField("CONNECTION_HANDLING"); getProperties().put("hibernate.connection.handling_mode", "DELAYED_ACQUISITION_AND_HOLD"); } catch (NoSuchFieldException ex) { // Try Hibernate 5.1 try { AvailableSettings.class.getField("ACQUIRE_CONNECTIONS"); getProperties().put("hibernate.connection.release_mode", "ON_CLOSE"); } catch (NoSuchFieldException ex2) { // on Hibernate 5.0.x or lower - no need to change the default there } } getProperties().put(AvailableSettings.CLASSLOADERS, Collections.singleton(resourceLoader.getClassLoader())); this.resourcePatternResolver = ResourcePatternUtils.getResourcePatternResolver(resourceLoader); }
Example #25
Source File: HibernateUtil.java From tutorials with MIT License | 5 votes |
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.proxy"); metadataSources.addAnnotatedClass(Company.class); metadataSources.addAnnotatedClass(Employee.class); Metadata metadata = metadataSources.buildMetadata(); return metadata.getSessionFactoryBuilder(); }
Example #26
Source File: SchemaUpdateTask.java From lams with GNU General Public License v2.0 | 5 votes |
private void configure(MetadataSources metadataSources) { for ( String filename : collectFiles() ) { if ( filename.endsWith( ".jar" ) ) { metadataSources.addJar( new File( filename ) ); } else { metadataSources.addFile( filename ); } } }
Example #27
Source File: ManagedResourcesImpl.java From lams with GNU General Public License v2.0 | 5 votes |
public static ManagedResourcesImpl baseline(MetadataSources sources, BootstrapContext bootstrapContext) { final ManagedResourcesImpl impl = new ManagedResourcesImpl(); bootstrapContext.getAttributeConverters().forEach( impl::addAttributeConverterDefinition ); impl.annotatedClassReferences.addAll( sources.getAnnotatedClasses() ); impl.annotatedClassNames.addAll( sources.getAnnotatedClassNames() ); impl.annotatedPackageNames.addAll( sources.getAnnotatedPackages() ); impl.mappingFileBindings.addAll( sources.getXmlBindings() ); return impl; }
Example #28
Source File: MetadataBuildingProcess.java From lams with GNU General Public License v2.0 | 5 votes |
/** * First step of 2-phase for MetadataSources->Metadata process * * @param sources The MetadataSources * @param bootstrapContext The bootstrapContext * * @return Token/memento representing all known users resources (classes, packages, mapping files, etc). */ public static ManagedResources prepare( final MetadataSources sources, final BootstrapContext bootstrapContext) { final ManagedResourcesImpl managedResources = ManagedResourcesImpl.baseline( sources, bootstrapContext ); ScanningCoordinator.INSTANCE.coordinateScan( managedResources, bootstrapContext, sources.getXmlMappingBinderAccess() ); return managedResources; }
Example #29
Source File: SchemaValidatorTask.java From lams with GNU General Public License v2.0 | 5 votes |
private void configure(MetadataSources metadataSources) { for ( String filename : collectFiles() ) { if ( filename.endsWith(".jar") ) { metadataSources.addJar( new File( filename ) ); } else { metadataSources.addFile( filename ); } } }
Example #30
Source File: HibernateUtil.java From tutorials with MIT License | 5 votes |
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) { MetadataSources metadataSources = new MetadataSources(serviceRegistry); metadataSources.addPackage("com.baeldung.hibernate.pojo"); metadataSources.addAnnotatedClass(Student.class); metadataSources.addAnnotatedClass(PointEntity.class); metadataSources.addAnnotatedClass(PolygonEntity.class); Metadata metadata = metadataSources.getMetadataBuilder() .build(); return metadata.getSessionFactoryBuilder() .build(); }