@Before
  public void setUp() throws Exception {
    serviceRegistry =
        new StandardServiceRegistryBuilder()
            .enableAutoClose()
            .applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop")
            .build();

    MetadataBuildingContext buildingContext =
        new MetadataBuildingContextTestingImpl(serviceRegistry);

    Properties properties = new Properties();
    properties.setProperty(SequenceGenerator.SEQUENCE, TEST_SEQUENCE);
    properties.setProperty(SequenceHiLoGenerator.MAX_LO, "3");
    properties.put(
        PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER,
        buildingContext.getObjectNameNormalizer());

    generator = new SequenceHiLoGenerator();
    generator.configure(
        StandardBasicTypes.LONG, properties, serviceRegistry.getService(JdbcEnvironment.class));

    Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
    generator.registerExportables(metadata.getDatabase());

    sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory();
  }
예제 #2
0
  private static SessionFactory init() {
    StandardServiceRegistry standardRegistry =
        new StandardServiceRegistryBuilder().configure().build();
    Metadata metadata =
        new MetadataSources(standardRegistry)
            .addAnnotatedClass(Actor.class)
            .addAnnotatedClass(Movie.class)
            .buildMetadata();

    return metadata.buildSessionFactory();
  }
예제 #3
0
 private static SessionFactory buildSessionFactory() {
   try {
     StandardServiceRegistry standardRegistry =
         new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
     Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder().build();
     return metadata.getSessionFactoryBuilder().build();
   } catch (HibernateException e) {
     System.out.println("Problema creando SessionFactory " + e);
   }
   return sessionFactory;
 }
  @Test
  public void testGeneratedUuidId() {
    StandardServiceRegistry ssr =
        new StandardServiceRegistryBuilder()
            .applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop")
            .build();
    try {
      Metadata metadata =
          new MetadataSources(ssr).addAnnotatedClass(TheEntity.class).buildMetadata();
      ((MetadataImpl) metadata).validate();

      PersistentClass entityBinding = metadata.getEntityBinding(TheEntity.class.getName());
      assertEquals(UUID.class, entityBinding.getIdentifier().getType().getReturnedClass());
      IdentifierGenerator generator =
          entityBinding
              .getIdentifier()
              .createIdentifierGenerator(
                  metadata.getIdentifierGeneratorFactory(),
                  metadata.getDatabase().getDialect(),
                  null,
                  null,
                  (RootClass) entityBinding);
      assertTyping(UUIDGenerator.class, generator);

      // now a functional test
      SessionFactory sf = metadata.buildSessionFactory();
      try {
        TheEntity theEntity = new TheEntity();

        Session s = sf.openSession();
        s.beginTransaction();
        s.save(theEntity);
        s.getTransaction().commit();
        s.close();

        assertNotNull(theEntity.id);

        s = sf.openSession();
        s.beginTransaction();
        s.delete(theEntity);
        s.getTransaction().commit();
        s.close();
      } finally {
        try {
          sf.close();
        } catch (Exception ignore) {
        }
      }
    } finally {
      StandardServiceRegistryBuilder.destroy(ssr);
    }
  }
  @Test
  public void testWithJpaCompliantNamingStrategy() throws Exception {
    Metadata metadata =
        new MetadataSources(serviceRegistry)
            .addAnnotatedClass(A.class)
            .addAnnotatedClass(AddressEntry.class)
            .getMetadataBuilder()
            .applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
            .build();

    Collection collectionBinding = metadata.getCollectionBinding(A.class.getName() + ".address");
    assertEquals(
        "Expecting A#address collection table name (implicit) to be [A_address] per JPA spec (section 11.1.8)",
        "A_ADDRESS",
        collectionBinding.getCollectionTable().getQuotedName().toUpperCase(Locale.ROOT));
  }
  @Before
  public void setUp() {
    AbstractMultiTenantConnectionProvider multiTenantConnectionProvider =
        buildMultiTenantConnectionProvider();

    Map settings = new HashMap();
    settings.put(Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
    settings.put(Environment.CACHE_REGION_FACTORY, CachingRegionFactory.class.getName());
    settings.put(Environment.GENERATE_STATISTICS, "true");

    serviceRegistry =
        (ServiceRegistryImplementor)
            new StandardServiceRegistryBuilder()
                .applySettings(settings)
                .addService(MultiTenantConnectionProvider.class, multiTenantConnectionProvider)
                .build();

    MetadataSources ms = new MetadataSources(serviceRegistry);
    ms.addAnnotatedClass(Customer.class);
    ms.addAnnotatedClass(Invoice.class);

    Metadata metadata = ms.buildMetadata();
    ((RootClass) metadata.getEntityBinding(Customer.class.getName()))
        .setCacheConcurrencyStrategy("read-write");

    HibernateSchemaManagementTool tool = new HibernateSchemaManagementTool();
    tool.injectServices(serviceRegistry);

    final GenerationTargetToDatabase acmeTarget =
        new GenerationTargetToDatabase(
            new DdlTransactionIsolatorTestingImpl(serviceRegistry, acmeProvider));
    final GenerationTargetToDatabase jbossTarget =
        new GenerationTargetToDatabase(
            new DdlTransactionIsolatorTestingImpl(serviceRegistry, jbossProvider));

    new SchemaDropperImpl(serviceRegistry)
        .doDrop(metadata, serviceRegistry, settings, true, acmeTarget, jbossTarget);

    new SchemaCreatorImpl(serviceRegistry)
        .doCreation(metadata, serviceRegistry, settings, true, acmeTarget, jbossTarget);

    final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
    configure(sfb);
    sessionFactory = (SessionFactoryImplementor) sfb.build();
  }
  @Override
  protected NameSpaceTablesInformation performTablesMigration(
      Metadata metadata,
      DatabaseInformation existingDatabase,
      ExecutionOptions options,
      Dialect dialect,
      Formatter formatter,
      Set<String> exportIdentifiers,
      boolean tryToCreateCatalogs,
      boolean tryToCreateSchemas,
      Set<Identifier> exportedCatalogs,
      Namespace namespace,
      GenerationTarget[] targets) {
    final NameSpaceTablesInformation tablesInformation =
        new NameSpaceTablesInformation(
            metadata.getDatabase().getJdbcEnvironment().getIdentifierHelper());

    if (schemaFilter.includeNamespace(namespace)) {
      createSchemaAndCatalog(
          existingDatabase,
          options,
          dialect,
          formatter,
          tryToCreateCatalogs,
          tryToCreateSchemas,
          exportedCatalogs,
          namespace,
          targets);
      final NameSpaceTablesInformation tables = existingDatabase.getTablesInformation(namespace);
      for (Table table : namespace.getTables()) {
        if (schemaFilter.includeTable(table) && table.isPhysicalTable()) {
          checkExportIdentifier(table, exportIdentifiers);
          final TableInformation tableInformation = tables.getTableInformation(table);
          if (tableInformation == null) {
            createTable(table, dialect, metadata, formatter, options, targets);
          } else if (tableInformation != null && tableInformation.isPhysicalTable()) {
            tablesInformation.addTableInformation(tableInformation);
            migrateTable(table, tableInformation, dialect, metadata, formatter, options, targets);
          }
        }
      }

      for (Table table : namespace.getTables()) {
        if (schemaFilter.includeTable(table) && table.isPhysicalTable()) {
          final TableInformation tableInformation = tablesInformation.getTableInformation(table);
          if (tableInformation == null
              || (tableInformation != null && tableInformation.isPhysicalTable())) {
            applyIndexes(table, tableInformation, dialect, metadata, formatter, options, targets);
            applyUniqueKeys(
                table, tableInformation, dialect, metadata, formatter, options, targets);
          }
        }
      }
    }
    return tablesInformation;
  }
  @Before
  public void setUp() throws Exception {
    BasicTestingJdbcServiceImpl jdbcServices = new BasicTestingJdbcServiceImpl();
    jdbcServices.prepare(false);

    serviceRegistry =
        new StandardServiceRegistryBuilder()
            .enableAutoClose()
            .addService(JdbcEnvironment.class, jdbcServices.getJdbcEnvironment())
            .addService(JdbcServices.class, jdbcServices)
            .applySetting(AvailableSettings.HBM2DDL_AUTO, "create-drop")
            .build();

    generator = new SequenceHiLoGenerator();

    // Build the properties used to configure the id generator
    Properties properties = new Properties();
    properties.setProperty(SequenceGenerator.SEQUENCE, TEST_SEQUENCE);
    properties.setProperty(SequenceHiLoGenerator.MAX_LO, "0"); // JPA allocationSize of 1
    properties.put(
        PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER,
        new ObjectNameNormalizer() {
          @Override
          protected MetadataBuildingContext getBuildingContext() {
            return new MetadataBuildingContextTestingImpl(serviceRegistry);
          }
        });
    generator.configure(StandardBasicTypes.LONG, properties, serviceRegistry);

    final Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
    metadata
        .getDatabase()
        .addAuxiliaryDatabaseObject(
            new SimpleAuxiliaryDatabaseObject(
                Collections.<String>emptySet(),
                null,
                null,
                generator.sqlCreateStrings(TestingDatabaseInfo.DIALECT),
                generator.sqlDropStrings(TestingDatabaseInfo.DIALECT)));

    sessionFactory = (SessionFactoryImplementor) metadata.buildSessionFactory();
  }
  /**
   * @param cfg
   * @param exporter
   * @param file
   */
  public void export(Configuration cfg, ConfigurationVisitor exporter) {

    Map<String, Component> components = new HashMap<String, Component>();
    Metadata md = getMetadata(cfg);

    for (Iterator<PersistentClass> classes = md.getEntityBindings().iterator();
        classes.hasNext(); ) {
      if (exporter.startMapping(cfg)) {
        PersistentClass clazz = classes.next();
        collectComponents(components, clazz);

        if (exporter.startPersistentClass(clazz)) {
          if (clazz.hasIdentifierProperty()) {
            exporter.startIdentifierProperty(clazz.getIdentifierProperty());
            exporter.endIdentifierProperty(clazz.getIdentifierProperty());
          } else if (clazz.hasEmbeddedIdentifier()) {
            exporter.startEmbeddedIdentifier((Component) clazz.getKey());
            exporter.endEmbeddedIdentifier((Component) clazz.getKey());
          }
          Iterator<?> unjoinedPropertyIterator = clazz.getUnjoinedPropertyIterator();
          while (unjoinedPropertyIterator.hasNext()) {
            Property prop = (Property) unjoinedPropertyIterator.next();
            exporter.startProperty(prop);
            exporter.endProperty(prop);
          }
        }
        exporter.endPersistentClass(clazz);
      } else {
        exporter.endMapping(cfg);
      }
    }

    for (Iterator<?> comps = components.values().iterator(); comps.hasNext(); ) {
      Component component = (Component) comps.next();
      exporter.startComponent(component);
    }

    if (exporter.startGeneralConfiguration(cfg)) exporter.endGeneralConfiguration(cfg);
  }
 @Override
 public Class<?> getClassMapping(String entityName) {
   return metadata.getEntityBinding(entityName).getMappedClass();
 }
 @Override
 public Iterator<Class<?>> getClassMappings() {
   return new ClassIterator(metadata.getEntityBindings().iterator());
 }