类org.hibernate.boot.MetadataSources源码实例Demo

下面列出了怎么用org.hibernate.boot.MetadataSources的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: tutorials   文件: NamedParameterUnitTest.java
@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);
    }
}
 
@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"
  );
}
 
/**
 * 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();
}
 
@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");
}
 
@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");
}
 
/**
 * 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();
}
 
@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);
    }
}
 
源代码8 项目: google-cloud-spanner-hibernate   文件: App.java
/**
 * 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();
}
 
/**
 * 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;
}
 
源代码10 项目: tutorials   文件: PersistJSONUnitTest.java
@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() + "]");
    }
}
 
源代码11 项目: tutorials   文件: HibernateUtil.java
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);
    }
}
 
源代码12 项目: tutorials   文件: HibernateUtil.java
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();

}
 
源代码13 项目: tutorials   文件: BootstrapAPIIntegrationTest.java
@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();
}
 
源代码14 项目: lams   文件: MappingReference.java
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;
		}
	}
}
 
源代码15 项目: Insights   文件: TestDal.java
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();
}
 
源代码16 项目: tutorials   文件: NamingStrategyLiveTest.java
@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() + "]");
    }
}
 
源代码17 项目: HibernateTips   文件: TestHibernateBootstrapping.java
@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();
}
 
源代码18 项目: tutorials   文件: HibernateUtil.java
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();

}
 
/**
 * 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();
}
 
源代码20 项目: tutorials   文件: HibernateUtil.java
/**
 * 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);
}
 
源代码21 项目: juddi   文件: App.java
/**
 * 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);
}
 
源代码22 项目: tutorials   文件: HibernateUtil.java
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();

}
 
源代码23 项目: tutorials   文件: HibernateAnnotationUtil.java
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);
    }
}
 
@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();
}
 
@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)"
  );
}
 
@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)"
  );
}
 
@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"
  );
}
 
@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"
  );
}
 
源代码29 项目: tutorials   文件: HibernateLifecycleUtil.java
private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
    MetadataSources metadataSources = new MetadataSources(serviceRegistry);
    metadataSources.addAnnotatedClass(FootballPlayer.class);

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

}
 
@Test
public void generateCreateStringsEmptyEntityTest() {
  assertThatThrownBy(() -> {
    Metadata metadata = new MetadataSources(this.registry)
        .addAnnotatedClass(EmptyEntity.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$EmptyEntity");
}
 
 类所在包
 同包方法