Example usage for org.hibernate.cfg Configuration addClass

List of usage examples for org.hibernate.cfg Configuration addClass

Introduction

In this page you can find the example usage for org.hibernate.cfg Configuration addClass.

Prototype

public Configuration addClass(Class persistentClass) throws MappingException 

Source Link

Document

Read a mapping as an application resource using the convention that a class named foo.bar.Foo is mapped by a file foo/bar/Foo.hbm.xml which can be resolved as a classpath resource.

Usage

From source file:com.gemstone.gemfire.modules.HibernateJUnitTest.java

License:Apache License

public static SessionFactory getSessionFactory(Properties overrideProps) {
    System.setProperty(DistributionConfig.GEMFIRE_PREFIX + "home", "GEMFIREHOME");
    Configuration cfg = new Configuration();
    cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
    cfg.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
    // cfg.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test");
    cfg.setProperty("hibernate.connection.url", jdbcURL);
    cfg.setProperty("hibernate.connection.username", "sa");
    cfg.setProperty("hibernate.connection.password", "");
    cfg.setProperty("hibernate.connection.pool_size", "1");
    cfg.setProperty("hibernate.connection.autocommit", "true");
    cfg.setProperty("hibernate.hbm2ddl.auto", "update");

    cfg.setProperty("hibernate.cache.region.factory_class",
            "com.gemstone.gemfire.modules.hibernate.GemFireRegionFactory");
    cfg.setProperty("hibernate.show_sql", "true");
    cfg.setProperty("hibernate.cache.use_query_cache", "true");
    //cfg.setProperty("gemfire.mcast-port", AvailablePort.getRandomAvailablePort(AvailablePort.JGROUPS)+"");
    cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + MCAST_PORT, "0");
    cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + STATISTIC_SAMPLING_ENABLED, "true");
    cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + LOG_FILE, gemfireLog);
    cfg.setProperty(DistributionConfig.GEMFIRE_PREFIX + "writable-working-dir", tmpDir.getPath());
    //cfg.setProperty("gemfire.statistic-archive-file", "plugin-stats-file.gfs");
    //cfg.setProperty("gemfire.default-client-region-attributes-id", "CACHING_PROXY");
    //cfg.setProperty("gemfire.cache-topology", "client-server");
    //cfg.setProperty("gemfire.locators", "localhost[5432]");
    //cfg.setProperty("gemfire.log-level", "fine");
    // cfg.setProperty("", "");
    cfg.addClass(Person.class);
    cfg.addClass(Event.class);
    if (overrideProps != null) {
        Iterator it = overrideProps.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            cfg.setProperty(key, overrideProps.getProperty(key));
        }//from w  w w.  j ava2s.c om
    }
    return cfg.buildSessionFactory();
}

From source file:com.opengamma.util.test.HibernateTest.java

License:Open Source License

@BeforeMethod
public void setUp() throws Exception {
    super.setUp();

    Configuration configuration = getDbTool().getTestHibernateConfiguration();
    for (Class<?> clazz : getHibernateMappingClasses()) {
        configuration.addClass(clazz);
    }//from  w ww. j  a  va  2s. c  o  m

    SessionFactory sessionFactory = configuration.buildSessionFactory();
    setSessionFactory(sessionFactory);
}

From source file:com.persistent.cloudninja.utils.SessionFactoryConfigurer.java

License:Apache License

public SessionFactory createSessionFactoryForTenant(String tenantDB) {
    TenantDataConnectionEntity dataConnectionEntity = tenantDataConnectionDao.find(tenantDB.substring(4));
    StringBuffer strBufServerURL = new StringBuffer("jdbc:sqlserver://");
    strBufServerURL.append(dataConnectionEntity.getServer());
    strBufServerURL.append(";databaseName=");
    strBufServerURL.append(tenantDB);/*w ww  .j  a v  a2s  . c o m*/
    strBufServerURL.append(";");

    String userName = dataConnectionEntity.getUser();
    String password = dataConnectionEntity.getPassword();

    Configuration cfg = new Configuration();
    cfg.addClass(TaskList.class);
    cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
    cfg.setProperty("hibernate.show_sql", "true");
    cfg.setProperty("hibernate.hbm2ddl.auto", "update");
    cfg.setProperty("hibernate.connection.driver_class", driverClassName);
    cfg.setProperty("hibernate.connection.url", strBufServerURL.toString());
    cfg.setProperty("hibernate.connection.username", userName);
    cfg.setProperty("hibernate.connection.password", password);

    return cfg.buildSessionFactory();
}

From source file:com.vecna.maven.hibernate.HibernateSchemaMojo.java

License:Apache License

/**
 * Create mapping metadata from provided Hibernate configuration
 * @return mapping metadata/*from   ww w.j a v  a 2s.  com*/
 * @throws MojoExecutionException if a mapping class cannot be resolved or if the naming strategy cannot be instantiated
 */
protected Configuration createMappings() throws MojoExecutionException {
    Configuration configuration = new AnnotationConfiguration();

    if (configFiles != null) {
        for (String configFile : configFiles) {
            if (configFile != null && !configFile.equals("")) {
                configuration.configure(getURL(configFile));
            }
        }
    }

    if (additionalClasses != null) {
        for (String additionalClass : additionalClasses) {
            try {
                configuration.addClass(Class.forName(additionalClass));
            } catch (ClassNotFoundException e) {
                throw new MojoExecutionException("coudn't add additional classes", e);
            }
        }
    }

    if (additionalMappings != null) {
        for (String mapping : additionalMappings) {
            configuration.addURL(getURL(mapping));
        }
    }

    if (propertyFiles != null) {
        for (String propertyFile : propertyFiles) {
            URL url = getURL(propertyFile);
            Properties properties = PropertyUtils.loadProperties(url);
            configuration.addProperties(properties);
        }
    }

    if (properties != null) {
        configuration.addProperties(properties);
    }

    if (namingStrategy != null) {
        try {
            @SuppressWarnings("unchecked")
            Class nsClass = Thread.currentThread().getContextClassLoader().loadClass(namingStrategy);
            configuration.setNamingStrategy((NamingStrategy) nsClass.newInstance());
        } catch (Exception e) {
            throw new MojoExecutionException(namingStrategy + " is not a valid naming strategy", e);
        }
    }

    configuration.buildMappings();

    if (!disableEnvers) {
        if (tryEnableEnvers(configuration)) {
            getLog().info("Detected Envers");
        }
    }

    return configuration;
}

From source file:de.erdesignerng.model.serializer.repository.HibernateTemplate.java

License:Open Source License

protected Configuration createConfiguration(Class aHibernateDialectClass) {
    Configuration theConfiguration = new Configuration();
    theConfiguration.addClass(DomainEntity.class);
    theConfiguration.addClass(CustomTypeEntity.class);
    theConfiguration.addClass(TableEntity.class);
    theConfiguration.addClass(AttributeEntity.class);
    theConfiguration.addClass(IndexEntity.class);
    theConfiguration.addClass(RelationEntity.class);
    theConfiguration.addClass(CommentEntity.class);
    theConfiguration.addClass(SubjectAreaEntity.class);
    theConfiguration.addClass(RepositoryEntity.class);
    theConfiguration.addClass(ChangeEntity.class);
    theConfiguration.addClass(ViewEntity.class);
    theConfiguration.setProperty(Environment.DIALECT, aHibernateDialectClass.getName());
    theConfiguration.setProperty(Environment.HBM2DDL_AUTO, "update");
    theConfiguration.setProperty(Environment.CONNECTION_PROVIDER,
            ThreadbasedConnectionProvider.class.getName());
    return theConfiguration;
}

From source file:de.nava.informa.impl.hibernate.SessionHandler.java

License:Open Source License

/**
 * Constructor which configures hibernate, in this order:
 * <ol>//from w  ww.  j  ava  2 s.c o  m
 * <li>Reads hibernate.cfg.xml or hibernate.properties file from the
 * CLASSPATH to retrieve information about how the database can be
 * accessed (JDBC connection properties).</li>
 * <li>Then reads in the definiton files for all related informa hibernate
 * classes (*.hbm.xml)</li>
 * <li>Finally, if supplied, applies a Properties object to do a final
 * override.</li>
 * </ol>
 *
 * @throws HibernateException In case a problem occurred while configuring
 *                            hibernate or creating the session factory.
 */
private SessionHandler(Properties props) throws HibernateException {
    // reads in hibernate.properties implictly for database connection settings
    Configuration cfg = new Configuration();

    // attempt to use standard config file named hibernate.cfg.xml
    try {
        cfg.configure();
    } catch (HibernateException he) {
        logger.info("Can't find \"hibernate.cfg.xml\" in classpath.");
    }

    // add base classes
    cfg.addClass(Channel.class).addClass(Item.class).addClass(ItemGuid.class).addClass(ItemEnclosure.class)
            .addClass(ItemSource.class).addClass(Cloud.class).addClass(Category.class)
            .addClass(ChannelGroup.class).addClass(ChannelSubscription.class).addClass(Image.class)
            .addClass(ItemMetadata.class).addClass(TextInput.class);

    // If Properties were supplied then use them as the final override
    if (props != null)
        cfg.addProperties(props);

    // get session factory (expensive)
    sessFactory = cfg.buildSessionFactory();
}

From source file:net.commerce.zocalo.hibernate.HibernateTestUtil.java

License:Open Source License

static public void initializeSessionFactory(String dbFilePath, boolean mode) {
    String connectionURL = HibernateUtil.connectionUrl(dbFilePath, mode);
    String schemaCreateMode = mode ? HibernateUtil.SCHEMA_CREATE : HibernateUtil.SCHEMA_UPDATE;
    try {// ww  w.  j a  va2s .  c om
        Configuration configuration = new Configuration();
        addClasses(configuration);
        configuration.addClass(MockDatum.class);
        if (connectionURL != null && !"".equals(connectionURL)) {
            configuration.setProperty("hibernate.connection.url", connectionURL);
        }
        configuration.setProperty("hibernate.hbm2ddl.auto", schemaCreateMode);

        sessionFactory.close();
        sessionFactory = configuration.buildSessionFactory();
        resetSession();
    } catch (HibernateException ex) {
        System.err.println(
                "Hibernate Exception Thrown in buildSessionFactory().  " + "Is HIBERNATE.JAR Missing?\n" + ex);
        throw new ExceptionInInitializerError(ex);
    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed for test." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:net.commerce.zocalo.hibernate.HibernateUtil.java

License:Open Source License

static void addClasses(Configuration configuration) {
    configuration.addClass(net.commerce.zocalo.claim.Claim.class);
    configuration.addClass(net.commerce.zocalo.claim.Position.class);
    configuration.addClass(net.commerce.zocalo.currency.CurrencyToken.class);
    configuration.addClass(net.commerce.zocalo.currency.Coupons.class);
    configuration.addClass(net.commerce.zocalo.currency.CashBank.class);
    configuration.addClass(net.commerce.zocalo.currency.CouponBank.class);
    configuration.addClass(net.commerce.zocalo.currency.Funds.class);
    //        configuration.addClass(net.commerce.zocalo.currency.Currency.class); // Using Table-per-concrete-subclass for Currency/Funds/Coupons
    configuration.addClass(net.commerce.zocalo.currency.Accounts.class);
    configuration.addClass(net.commerce.zocalo.orders.Order.class);
    configuration.addClass(net.commerce.zocalo.orders.SortedOrders.class);
    configuration.addClass(net.commerce.zocalo.user.SecureUser.class);
    configuration.addClass(net.commerce.zocalo.user.UnconfirmedUser.class);
    configuration.addClass(net.commerce.zocalo.market.Market.class);
    configuration.addClass(net.commerce.zocalo.market.MarketMaker.class);
    configuration.addClass(net.commerce.zocalo.market.Book.class);
    configuration.addClass(net.commerce.zocalo.market.Outcome.class);
    configuration.addClass(net.commerce.zocalo.ajax.events.Ask.class);
    configuration.addClass(net.commerce.zocalo.ajax.events.Bid.class);
    configuration.addClass(net.commerce.zocalo.ajax.events.BestAsk.class);
    configuration.addClass(net.commerce.zocalo.ajax.events.BestBid.class);
    configuration.addClass(net.commerce.zocalo.ajax.events.Trade.class); // using table-per-hierarchy for BookTrade/MakerTrade
    configuration.addClass(net.commerce.zocalo.ajax.events.SelfDealing.class);
    configuration.addClass(net.commerce.zocalo.ajax.events.OrderRemoval.class);
    configuration.addClass(net.commerce.zocalo.ajax.events.Redemption.class);
    //        configuration.addClass(net.commerce.zocalo.currency.Quantity.class);        // Always a component
    //        configuration.addClass(net.commerce.zocalo.currency.Probability.class);     // Always a component
    //        configuration.addClass(net.commerce.zocalo.currency.Price.class);           // Always a component
}

From source file:net.sf.oreka.persistent.HbnXmlTest.java

License:Open Source License

/**
 * @param args the command line arguments
 *///  w  w  w. ja v a2  s  . c  om
public static void main(String[] args) {

    Configuration config = new Configuration().configure("mysql.hbm.xml");

    config.addClass(HbnXmlTestClass.class);
    SessionFactory sessions = config.buildSessionFactory();
    Session session = sessions.openSession();

    Transaction tx = null;

    try {
        /*
           SchemaExport export = new SchemaExport(config);
           export.setOutputFile("c:\\schema.sql");
           export.create(true,false);
           */

        for (int i = 0; i < 100; i++) {
            tx = session.beginTransaction();

            HbnXmlTestClass obj = new HbnXmlTestClass();

            session.save(obj);
            tx.commit();
        }

        // insert
        /*
        for (int i=0; i<100 ; i++)
        {
            tx = session.beginTransaction();
                
         RecSession RecSession = new RecSession();
         RecSession.setDuration(i);
                 
                 
         RecSegment intr1 = new RecSegment();
         intr1.setRecSession(RecSession);
         intr1.setLocalParty(i + " " + 1);
         intr1.setDuration(23);
         RecSegment intr2 = new RecSegment();
         intr2.setRecSession(RecSession);
         intr2.setLocalParty(i + " " + 2);
         intr2.setDuration(45);
                 
         session.save(RecSession);
         session.save(intr1);
         session.save(intr2);            
            tx.commit();
        }
        */
        /*
        // iterator select
        Iterator documents = session.createQuery(
              "from Documents doc join doc.car")
              .list()
              .iterator();
                
        while ( documents.hasNext() ) {
            Object[] row = (Object[]) documents.next();
            Documents doc  = (Documents)row[0];
            Car car  = (Car)row[1];
                   
           //Documents doc = (Documents)documents.next();
                   
           System.out.println(doc.getId() + " " + car.getId());
        }
        */
        /*
        // scrollable select
        ScrollableResults scrollDocs = session.createQuery(
             "from RecSegment intr join intr.RecSession").scroll();
        if ( scrollDocs.last() ) {
           System.out.println("Num res:" + scrollDocs.getRowNumber() + "\n\n");   
        }
                
        scrollDocs.beforeFirst();
        while (scrollDocs.next())
        {
           RecSegment doc  = (RecSegment)scrollDocs.get(0);
           RecSession car  = (RecSession)scrollDocs.get(1);   
           System.out.println(doc.getId() + " " + car.getId());         
        }
        */

        /*
        // many to many insert
           tx = session.beginTransaction();
                
        RecProgram prog1 = new RecProgram();
        RecProgram prog2 = new RecProgram();         
        RecSegment seg = new RecSegment();
                
        HashSet programs = new HashSet();
        programs.add(prog1);
        programs.add(prog2);
        seg.setRecPrograms(programs);
                
        session.save(prog1);
        session.save(prog2);
        session.save(seg);            
           tx.commit();
           */

        // Many to many select
        /*
        ScrollableResults scrollDocs = session.createQuery(
        "from RecSegment as seg join seg.recPrograms as prg where prg.id=2").scroll();
        if ( scrollDocs.last() ) {
           System.out.println("Num res:" + scrollDocs.getRowNumber() + "\n\n");   
        }
                
        scrollDocs.beforeFirst();
        while (scrollDocs.next())
        {
           RecSegment seg  = (RecSegment)scrollDocs.get(0);
           RecProgram prg  = (RecProgram)scrollDocs.get(1);   
           System.out.println(seg.getId() + " " + prg.getId());         
        }
        */

        /*
        // one to one create
           tx = session.beginTransaction();
                
        RecProgram prog = new RecProgram();         
        User user = new User();
        prog.setTargetUser(user);
                
        session.save(user);
        session.save(prog);   
           tx.commit();
        */
        /*
        // one to one select
        ScrollableResults scrollDocs = session.createQuery(
        "from RecProgram as prg join prg.targetUser as tgt").scroll();
        if ( scrollDocs.last() ) {
           System.out.println("Num res:" + scrollDocs.getRowNumber() + "\n\n");   
        }
                
        scrollDocs.beforeFirst();
        while (scrollDocs.next())
        {
           RecProgram prg  = (RecProgram)scrollDocs.get(0);   
           User tgt  = (User)scrollDocs.get(1);
           System.out.println(prg.getId() + " " + tgt.getId());         
        }
        */
    } catch (HibernateException he) {
        throw he;
    } finally {
        session.close();
    }
}

From source file:no.abmu.finances.domain.fixtures.FinancesDbHibernate3TestFixture.java

License:Open Source License

/**
 * Creates hibernate3 sessionFactory with finances classes and 
 * organisationRegister classes for testing of finance module. 
 * /*from  w ww. j  a va 2 s . c o  m*/
 * The created sessionFactory is based on HSQLDB in memory database, 
 * this sessionFactory is for testing only and must not be used 
 * in production.
 * 
 * @return Hibernate3 SessionFactory of user Register.
 * @throws Exception if Hibernate fails to configure or create the 
 * specified sessionFactory.
 */
public static SessionFactory createFinancesAndOrgRegisterFactory() throws Exception {
    Configuration configuration = createConfiguration();

    addFinancesClasses(configuration);
    configuration.addClass(no.abmu.finances.domain.AccountOrgUnitMapping.class);
    configuration.addClass(no.abmu.finances.domain.ReportDataOrgUnitMapping.class);

    addOrganisationRegisterClasses(configuration);

    configuration.generateSchemaCreationScript(new HSQLDialect());
    return configuration.buildSessionFactory();
}