Example usage for org.hibernate.cfg Configuration configure

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

Introduction

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

Prototype

@Deprecated
public Configuration configure(org.w3c.dom.Document document) throws HibernateException 

Source Link

Usage

From source file:com.cosw.productsmaster.main.Main.java

public static void main(String a[]) {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
            .buildServiceRegistry();//w w  w . ja va 2  s . c o m
    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();

    //Aqui va codigo de pruebas

    Query q2 = session.createQuery(
            "SELECT e.pedidos from Envio e inner join e.pedidos as p inner join p.detalleCompras as detalleP inner join detalleP.productos as prod inner join prod.proveedores as prov where (prov.idProveedores = 1) and (day(e.fechaSalida) < day(:finalDate)) GROUP BY prov");

    List<Pedido> p = q2.list();

    for (Pedido p1 : p) {
        System.out.println("Fecha" + p1.getFechaLlegada().toString());
    }

    tx.commit();
    session.close();
}

From source file:com.cosw.superstuff.main.Main.java

public static void main(String a[]) {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
            .buildServiceRegistry();/*ww  w  .j  a  v  a2  s. c  om*/
    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();

    //Aqui va codigo de pruebas

    Query q2 = session
            .createQuery("SELECT t from Tendero tend INNER JOIN tend.tiendas t WHERE tend.idTenderos = 4961");

    List<Tienda> p = q2.list();

    for (Tienda p1 : p) {
        System.out.println("Fecha" + p1.getNombre());
    }

    tx.commit();
    session.close();
}

From source file:com.cosw.test.TestsFunciones.java

@BeforeClass
public static void setUp() {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate-pruebas-h2.cfg.xml");
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
            .buildServiceRegistry();/* w w w  . j a  v  a 2  s.  c o  m*/
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    session = sessionFactory.openSession();

    Pais p = new Pais("Francia", "PA", "FR", Pais.SIHAYCOBERTURA);
    Pais p1 = new Pais("Colombia", "COL", "ESPAOL", Pais.SIHAYCOBERTURA);

    Set<Lugar> lugares = new LinkedHashSet<>();
    Lugar l = new Lugar(p, "Paris", "Louvrie");
    lugares.add(new Lugar(p1, "Bogot", "Cedritos"));

    p1.setLugares(lugares);

    Proveedor proveedor = new Proveedor(1, l, "Hacemos zapatos", "Calle 123", "6701349", "NA", "NA");
    Proveedor proveedor1 = new Proveedor(2, l, "Hacemos Dulce", "Calle 123", "6701349", "NA", "NA");
    Proveedor proveedor2 = new Proveedor(3, l, "Hacemos Colonias", "Calle 123", "6701349", "NA", "NA");
    Proveedor proveedor3 = new Proveedor(4, l, "Hacemos Pokemones", "Calle 123", "6701349", "NA", "NA");
    Proveedor proveedor4 = new Proveedor(5, l, "Hacemos Casas", "Calle 123", "6701349", "NA", "NA");
    Proveedor proveedor5 = new Proveedor(6, l, "Hacemos Carros", "Calle 123", "6701349", "NA", "NA");
    Proveedor proveedor6 = new Proveedor(7, l, "Hacemos Aguacate", "Calle 123", "6701349", "NA", "NA");
    Proveedor proveedor7 = new Proveedor(8, l, "Hacemos Arroces", "Calle 123", "6701349", "NA", "NA");

    Categoria c = new Categoria(1, "Frutas", "Categoria que agrupa las frutas");
    Categoria c1 = new Categoria(100, "Alcohol", "Categoria que agrupa Bebidas Alcoholicas");
    Descuento d = new Descuento(0, new Date(), new Date(), "Esto es un descuento del 0%");
    Descuento d1 = new Descuento(100, new Date(), new Date(), "Esto es un descuento del 10%");

    session.save(d);
    session.save(d1);

    session.save(c);
    session.save(c1);

    session.save(p);
    session.save(p1);
    session.save(new Pais("Panama", "P", "ESPAOL", "1"));
    session.save(new Pais("Chile", "CL", "ESPAOL", "2"));

    session.save(l);

    session.save(proveedor);
    session.save(proveedor1);
    session.save(proveedor2);
    session.save(proveedor3);
    session.save(proveedor4);
    session.save(proveedor5);
    session.save(proveedor6);
    session.save(proveedor7);

    session.save(new Producto(1, c, d, "Banano", proveedor, 300));
    session.save(new Producto(2, c, d, "Manzana", proveedor1, 200));
    session.save(new Producto(3, c, d, "Pera", proveedor2, 200));
    session.save(new Producto(4, c, d, "Anana", proveedor3, 1000));
    session.save(new Producto(100, c, d, "Banano", proveedor4, 300));
    session.save(new Producto(200, c, d, "Manzana", proveedor5, 200));
    session.save(new Producto(300, c, d, "Pera", proveedor6, 200));
    session.save(new Producto(400, c, d, "Anana", proveedor7, 1000));
}

From source file:com.cosylab.cdb.jdal.hibernate.HibernateUtil.java

License:Open Source License

/**
 * Use default configuration and add properties from Properties.
 * Build session factory from combined configuration.
 * @param config/*from   w ww  . j av  a 2s .c  o m*/
 */
public void setConfiguration(Properties extraProperties) {
    try {
        Configuration config = new AnnotationConfiguration();
        config.configure(getConfigurationFileName());
        config.addProperties(extraProperties);
        sessionFactory = config.buildSessionFactory();
        configuration = config;
    } catch (Throwable ex) {
        // We have to catch Throwable, otherwise we will miss
        // NoClassDefFoundError and other subclasses of Error
        logger.log(Level.SEVERE, "Building SessionFactory failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.daniel.testehibernate.conexao.HibernateUtil.java

private static SessionFactory buildSessionFactory() {
    try {//from   ww w. j  a v  a  2  s  .com
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder registradorService = new StandardServiceRegistryBuilder();
        registradorService.applySettings(cfg.getProperties());
        StandardServiceRegistry servico = registradorService.build();
        return cfg.buildSessionFactory(servico);
    } catch (Exception e) {
        System.err.println("Criao inicial do objeto session factory falhou. Erro:" + e);
        throw new ExceptionInInitializerError(e);
    }
}

From source file:com.dao.SessionUtil.java

private SessionUtil() {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");

    sessionFactory = configuration.buildSessionFactory();
}

From source file:com.Dao.UsuarioDao.java

public UsuarioDao() {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
    factory = configuration.buildSessionFactory(serviceRegistry);

}

From source file:com.deskind.tradeoptimization.utils.HibernateUtils.java

public static SessionFactory getSessionFactory(String s) {
    if (sessionFactory == null) {
        Configuration configuration = new Configuration();
        configuration.configure(s);
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        sessionFactory = configuration.buildSessionFactory(ssrb.build());
    }// w  w w.j  a va  2  s .c om
    return sessionFactory;
}

From source file:com.fharms.marshalling.utils.HibernateTestUtil.java

License:Open Source License

public static SessionFactory getSessionFactory() {
    try {/*  w w  w .j  a  v a  2s. c  o  m*/
        if (sessionFactory == null) {
            URL configFile = HibernateTestUtil.class.getClassLoader().getResource("META-INF/hibernate.cfg.xml");
            Configuration configuration = new Configuration();
            configuration.configure(configFile); // configures settings from hibernate.cfg.xml
            StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
    } catch (Throwable ex) {
        throw new ExceptionInInitializerError(ex);
    }
    return sessionFactory;
}

From source file:com.frameworkset.common.poolman.hibernate.LocalSessionFactoryBean.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
protected SessionFactory buildSessionFactory() throws Exception {
    // Create Configuration instance.
    Configuration config = newConfiguration();

    DataSource dataSource = getDataSource();

    if (dataSource != null) {
        this.configTimeDataSourceHolder.set(dataSource);
    }//w w w  . ja  v  a  2  s  .com
    // Analogous to Hibernate EntityManager's Ejb3Configuration:
    // Hibernate doesn't allow setting the bean ClassLoader explicitly,
    // so we need to expose it as thread context ClassLoader accordingly.
    Thread currentThread = Thread.currentThread();
    ClassLoader threadContextClassLoader = currentThread.getContextClassLoader();
    boolean overrideClassLoader = (this.beanClassLoader != null
            && !this.beanClassLoader.equals(threadContextClassLoader));
    try {
        if (overrideClassLoader) {
            currentThread.setContextClassLoader(this.beanClassLoader);
        }

        if (this.entityInterceptor != null) {
            // Set given entity interceptor at SessionFactory level.
            config.setInterceptor(this.entityInterceptor);
        }

        if (this.namingStrategy != null) {
            // Pass given naming strategy to Hibernate Configuration.
            config.setNamingStrategy(this.namingStrategy);
        }

        if (this.configLocations != null) {
            for (Resource resource : this.configLocations) {
                // Load Hibernate configuration from given location.
                config.configure(resource.getURL());
            }
        }

        if (this.hibernateProperties != null) {
            // Add given Hibernate properties to Configuration.
            Properties temp = new Properties();
            temp.putAll(this.hibernateProperties);
            config.addProperties(temp);
        }

        if (dataSource != null) {
            Class providerClass = LocalDataSourceConnectionProvider.class;

            config.setProperty(Environment.CONNECTION_PROVIDER, providerClass.getName());
        }

        if (this.mappingResources != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (String mapping : this.mappingResources) {
                Resource resource = new ClassPathResource(mapping.trim(), this.beanClassLoader);
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.mappingLocations != null) {
            // Register given Hibernate mapping definitions, contained in resource files.
            for (Resource resource : this.mappingLocations) {
                config.addInputStream(resource.getInputStream());
            }
        }

        if (this.cacheableMappingLocations != null) {
            // Register given cacheable Hibernate mapping definitions, read from the file system.
            for (Resource resource : this.cacheableMappingLocations) {
                config.addCacheableFile(resource.getFile());
            }
        }

        if (this.mappingJarLocations != null) {
            // Register given Hibernate mapping definitions, contained in jar files.
            for (Resource resource : this.mappingJarLocations) {
                config.addJar(resource.getFile());
            }
        }

        if (this.mappingDirectoryLocations != null) {
            // Register all Hibernate mapping definitions in the given directories.
            for (Resource resource : this.mappingDirectoryLocations) {
                File file = resource.getFile();
                if (!file.isDirectory()) {
                    throw new IllegalArgumentException(
                            "Mapping directory location [" + resource + "] does not denote a directory");
                }
                config.addDirectory(file);
            }
        }

        // Tell Hibernate to eagerly compile the mappings that we registered,
        // for availability of the mapping information in further processing.
        postProcessMappings(config);
        config.buildMappings();

        if (this.entityCacheStrategies != null) {
            // Register cache strategies for mapped entities.
            for (Enumeration classNames = this.entityCacheStrategies.propertyNames(); classNames
                    .hasMoreElements();) {
                String className = (String) classNames.nextElement();
                String[] strategyAndRegion = SimpleStringUtil
                        .commaDelimitedListToStringArray(this.entityCacheStrategies.getProperty(className));
                if (strategyAndRegion.length > 1) {
                    // method signature declares return type as Configuration on Hibernate 3.6
                    // but as void on Hibernate 3.3 and 3.5
                    Method setCacheConcurrencyStrategy = Configuration.class
                            .getMethod("setCacheConcurrencyStrategy", String.class, String.class, String.class);
                    ReflectionUtils.invokeMethod(setCacheConcurrencyStrategy, config,
                            new Object[] { className, strategyAndRegion[0], strategyAndRegion[1] });
                } else if (strategyAndRegion.length > 0) {
                    config.setCacheConcurrencyStrategy(className, strategyAndRegion[0]);
                }
            }
        }

        if (this.collectionCacheStrategies != null) {
            // Register cache strategies for mapped collections.
            for (Enumeration collRoles = this.collectionCacheStrategies.propertyNames(); collRoles
                    .hasMoreElements();) {
                String collRole = (String) collRoles.nextElement();
                String[] strategyAndRegion = SimpleStringUtil
                        .commaDelimitedListToStringArray(this.collectionCacheStrategies.getProperty(collRole));
                if (strategyAndRegion.length > 1) {
                    config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0],
                            strategyAndRegion[1]);
                } else if (strategyAndRegion.length > 0) {
                    config.setCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]);
                }
            }
        }

        if (this.eventListeners != null) {
            // Register specified Hibernate event listeners.
            for (Map.Entry<String, Object> entry : this.eventListeners.entrySet()) {
                String listenerType = entry.getKey();
                Object listenerObject = entry.getValue();
                if (listenerObject instanceof Collection) {
                    Collection<Object> listeners = (Collection<Object>) listenerObject;
                    EventListeners listenerRegistry = config.getEventListeners();
                    Object[] listenerArray = (Object[]) Array
                            .newInstance(listenerRegistry.getListenerClassFor(listenerType), listeners.size());
                    listenerArray = listeners.toArray(listenerArray);
                    config.setListeners(listenerType, listenerArray);
                } else {
                    config.setListener(listenerType, listenerObject);
                }
            }
        }

        // Perform custom post-processing in subclasses.
        postProcessConfiguration(config);

        // Build SessionFactory instance.
        logger.info("Building new Hibernate SessionFactory");
        this.configuration = config;
        return newSessionFactory(config);
    }

    finally {

        if (overrideClassLoader) {
            // Reset original thread context ClassLoader.
            currentThread.setContextClassLoader(threadContextClassLoader);
        }
        configTimeDataSourceHolder.set(null);
    }
}