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 Project: tutorials   Author: eugenp   File: NamedParameterUnitTest.java    License: MIT License 6 votes vote down vote up
@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 #2
Source Project: google-cloud-spanner-hibernate   Author: GoogleCloudPlatform   File: TransactionsTest.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #3
@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 #4
Source Project: google-cloud-spanner-hibernate   Author: GoogleCloudPlatform   File: SpannerTableExporterTests.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #5
Source Project: google-cloud-spanner-hibernate   Author: GoogleCloudPlatform   File: SpannerTableExporterTests.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #6
Source Project: google-cloud-spanner-hibernate   Author: GoogleCloudPlatform   File: SpannerTableExporterTests.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #7
/**
 * 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 #8
Source Project: tutorials   Author: eugenp   File: HibernateLoggingIntegrationTest.java    License: MIT License 6 votes vote down vote up
@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 Project: google-cloud-spanner-hibernate   Author: GoogleCloudPlatform   File: App.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 #10
Source Project: java-technology-stack   Author: codeEngraver   File: LocalSessionFactoryBean.java    License: MIT License 6 votes vote down vote up
/**
 * 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 #11
Source Project: tutorials   Author: eugenp   File: PersistJSONUnitTest.java    License: MIT License 6 votes vote down vote up
@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 #12
Source Project: tutorials   Author: eugenp   File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
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 #13
Source Project: tutorials   Author: eugenp   File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
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 #14
Source Project: tutorials   Author: eugenp   File: BootstrapAPIIntegrationTest.java    License: MIT License 6 votes vote down vote up
@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 #15
Source Project: lams   Author: lamsfoundation   File: MappingReference.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 #16
Source Project: Insights   Author: CognizantOneDevOps   File: TestDal.java    License: Apache License 2.0 6 votes vote down vote up
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 #17
Source Project: tutorials   Author: eugenp   File: NamingStrategyLiveTest.java    License: MIT License 6 votes vote down vote up
@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 #18
Source Project: HibernateTips   Author: thjanssen   File: TestHibernateBootstrapping.java    License: MIT License 6 votes vote down vote up
@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 #19
Source Project: tutorials   Author: eugenp   File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
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 #20
Source Project: java-docs-samples   Author: GoogleCloudPlatform   File: HibernateSampleApplication.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 #21
Source Project: tutorials   Author: eugenp   File: HibernateUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 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 #22
Source Project: juddi   Author: apache   File: App.java    License: Apache License 2.0 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 #23
Source Project: tutorials   Author: eugenp   File: HibernateUtil.java    License: MIT License 5 votes vote down vote up
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 #24
Source Project: tutorials   Author: eugenp   File: HibernateAnnotationUtil.java    License: MIT License 5 votes vote down vote up
private static SessionFactory buildSessionFactory() {
    try {
        // Create the SessionFactory from hibernate-annotation.cfg.xml
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build();
        Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
        SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();

        return sessionFactory;

    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
}
 
Example #25
Source Project: hibernate-reactive   Author: hibernate   File: StandAloneReactiveTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void createReactiveSessionFactory() {
	StandardServiceRegistry registry = new ReactiveServiceRegistryBuilder()
			.applySetting( Settings.TRANSACTION_COORDINATOR_STRATEGY, "jta" )
			.applySetting( Settings.DIALECT, PostgreSQL9Dialect.class.getName() )
			.build();

	Stage.SessionFactory factory = new MetadataSources( registry )
			.buildMetadata()
			.getSessionFactoryBuilder()
			.build()
			.unwrap( Stage.SessionFactory.class );

	assertThat( factory ).isNotNull();
}
 
Example #26
@Test
public void testCreateInterleavedTables() {
  Metadata metadata =
      new MetadataSources(this.registry)
          .addAnnotatedClass(Child.class)
          .addAnnotatedClass(GrandParent.class)
          .addAnnotatedClass(Parent.class)
          .buildMetadata();

  Session session = metadata.buildSessionFactory().openSession();
  session.beginTransaction();
  session.close();

  List<String> sqlStrings =
      connection.getStatementResultSetHandler().getExecutedStatements();

  assertThat(sqlStrings).containsExactly(
      "START BATCH DDL",
      "RUN BATCH",
      "START BATCH DDL",
      "create table GrandParent (grandParentId INT64 not null,name STRING(255)) "
          + "PRIMARY KEY (grandParentId)",
      "create table Parent (grandParentId INT64 not null,"
          + "parentId INT64 not null,name STRING(255)) PRIMARY KEY (grandParentId,parentId), "
          + "INTERLEAVE IN PARENT GrandParent",
      "create table Child (childId INT64 not null,grandParentId INT64 not null,"
          + "parentId INT64 not null,name STRING(255)) "
          + "PRIMARY KEY (grandParentId,parentId,childId), "
          + "INTERLEAVE IN PARENT Parent",
      "create table hibernate_sequence (next_val INT64) PRIMARY KEY ()",
      "RUN BATCH",
      "INSERT INTO hibernate_sequence (next_val) VALUES(1)"
  );
}
 
Example #27
@Test
public void testCreateTables() {
  Metadata metadata =
      new MetadataSources(this.registry)
          .addAnnotatedClass(Employee.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 Employee "
          + "(id INT64 not null,name STRING(255),manager_id INT64) PRIMARY KEY (id)",
      "create table hibernate_sequence (next_val INT64) PRIMARY KEY ()",
      "create index name_index on Employee (name)",
      "alter table Employee add constraint FKiralam2duuhr33k8a10aoc2t6 "
          + "foreign key (manager_id) references Employee (id)",
      "RUN BATCH",
      "INSERT INTO hibernate_sequence (next_val) VALUES(1)"
  );
}
 
Example #28
@Test
public void testDropTables() throws SQLException {
  Metadata metadata =
      new MetadataSources(this.registry)
          .addAnnotatedClass(Employee.class)
          .buildMetadata();

  this.connection.setMetaData(MockJdbcUtils.metaDataBuilder()
      .setTables("Employee", "hibernate_sequence")
      .setIndices("name_index")
      .build());

  Session session = metadata.buildSessionFactory().openSession();
  session.beginTransaction();
  session.close();

  List<String> sqlStrings =
      this.connection.getStatementResultSetHandler().getExecutedStatements();

  assertThat(sqlStrings).startsWith(
      "START BATCH DDL",
      "drop index name_index",
      "drop table Employee",
      "drop table hibernate_sequence",
      "RUN BATCH"
  );
}
 
Example #29
@Test
public void testCreateUniqueIndexes_oneToMany() throws SQLException {
  Metadata metadata =
      new MetadataSources(this.registry)
          .addAnnotatedClass(Airport.class)
          .addAnnotatedClass(Airplane.class)
          .buildMetadata();

  Session session = metadata.buildSessionFactory().openSession();
  session.beginTransaction();
  session.close();

  List<String> sqlStrings =
      this.connection.getStatementResultSetHandler().getExecutedStatements();

  // Note that Hibernate generates a unique column for @OneToMany relationships because
  // one object is mapped to many others; this is distinct from the @ManyToMany case.
  // See: https://hibernate.atlassian.net/browse/HHH-3410
  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 table Airport (id STRING(255) not null) PRIMARY KEY (id)",
      "create table Airport_Airplane (Airport_id STRING(255) not null,"
          + "airplanes_id STRING(255) not null) PRIMARY KEY (Airport_id,airplanes_id)",
      "create unique index UK_gc568wb30sampsuirwne5jqgh on Airplane (modelName)",
      "create unique index UK_em0lqvwoqdwt29x0b0r010be on Airport_Airplane (airplanes_id)",
      "alter table Airport_Airplane add constraint FKkn0enwaxbwk7csf52x0eps73d "
          + "foreign key (airplanes_id) references Airplane (id)",
      "alter table Airport_Airplane add constraint FKh186t28ublke8o13fo4ppogs7 "
          + "foreign key (Airport_id) references Airport (id)",
      "RUN BATCH"
  );
}
 
Example #30
Source Project: tutorials   Author: eugenp   File: HibernateLifecycleUtil.java    License: MIT License 5 votes vote down vote up
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
    MetadataSources metadataSources = new MetadataSources(serviceRegistry);
    metadataSources.addAnnotatedClass(FootballPlayer.class);

    Metadata metadata = metadataSources.buildMetadata();
    return metadata.getSessionFactoryBuilder();

}