Example usage for org.hibernate.cfg Configuration getProperties

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

Introduction

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

Prototype

public Properties getProperties() 

Source Link

Document

Get all properties

Usage

From source file:com.baran.hibernate.HibernateOp.java

License:Open Source License

public static Session prepare() {
    Configuration configuration = new Configuration();
    configuration.configure("hibernate.cfg.xml");
    ServiceRegistryBuilder serviceRegistryBuilder = new ServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration
            .buildSessionFactory(serviceRegistryBuilder.buildServiceRegistry());
    Session session = sessionFactory.openSession();

    return session;
}

From source file:com.baymet.dolu.util.HibernateUtil.java

License:Apache License

public static SessionFactory createSessionFactory() {
    Configuration configuration = new Configuration();
    configuration.configure();/* w ww .  j  a va  2  s. c  om*/

    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}

From source file:com.bearingpoint.dao.impl.BookDao.java

private static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
    return sessionFactory;
}

From source file:com.beingjavaguys.onetableperclasshierarchy.HibernateMain.java

License:Open Source License

public static void main(String[] args) {

    Shape shape = new Shape("Sqaure");
    Rectangle rectangle = new Rectangle("Rectangle", 10, 20);
    Circle circle = new Circle("Circle", 4);

    Configuration configuration = new Configuration();
    configuration.configure();//from   ww  w.  j ava2  s  .  c  om
    ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
            .buildServiceRegistry();
    SessionFactory sf = configuration.buildSessionFactory(sr);
    Session ss = sf.openSession();

    ss.beginTransaction();
    ss.save(shape);
    ss.save(rectangle);
    ss.save(circle);
    ss.getTransaction().commit();
    ss.close();

}

From source file:com.blackcrowsys.bcslog.server.tasks.DbConnectionManager.java

License:Open Source License

@Override
public Integer call() throws Exception {
    while (threadFlag.isCarryOnDbOperation()) {
        if (!threadFlag.isDbConnectionOpen()) {
            try {
                Configuration cfg = new Configuration().addProperties(sharedObjectWrapper.getDbProperties());
                serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties())
                        .build();/*from ww  w.ja  v  a 2s.c  om*/
                sharedObjectWrapper.setLogsDao(DaoFactory.getLogsDao(cfg.buildSessionFactory(serviceRegistry)));
                threadFlag.setDbConnectionOpen(true);
            } catch (HibernateException e) {
                threadFlag.setDbConnectionOpen(false);
                e.printStackTrace();
            }
        }
        Thread.sleep(SLEEP);
    }
    System.out.println("SQL Connection Manager: exiting");
    return ReturnCode.OKAY.getValue();
}

From source file:com.bookshop.utility.HibernateUtil.java

public static SessionFactory configureSessionFactory() throws HibernateException {
    Configuration configuration = new Configuration();

    configuration.configure();/*from ww  w . ja v  a 2  s.  co m*/

    StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();

    serviceRegistryBuilder.applySettings(configuration.getProperties());

    serviceRegistry = serviceRegistryBuilder.build();

    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    return sessionFactory;
}

From source file:com.clican.pluto.orm.dynamic.impl.DataBaseOperationImpl.java

License:LGPL

@SuppressWarnings("unchecked")
public void alterTable(Configuration cfg, ModelDescription oldOne, ModelDescription newOne) {
    Connection conn = null;//  w  w w  . j  a v a 2 s .  c  o m
    DatabaseMetadata meta = null;
    String defaultCatalog = cfg.getProperties().getProperty(Environment.DEFAULT_CATALOG);
    String defaultSchema = cfg.getProperties().getProperty(Environment.DEFAULT_SCHEMA);
    List<String> alterSqls = new ArrayList<String>();
    try {
        conn = dataSource.getConnection();
        meta = new DatabaseMetadata(conn, dialect);
        Mapping mapping = cfg.buildMapping();
        // Alter table name;
        if (!oldOne.getName().equals(newOne.getName())) {
            String alterTableName = "alter table " + dialect.openQuote() + oldOne.getName().toUpperCase()
                    + dialect.closeQuote() + "rename to " + dialect.openQuote() + newOne.getName().toUpperCase()
                    + dialect.closeQuote();
            executeSql(conn, alterTableName);
        }

        List<PropertyDescription> oldPropertyDescriptionList = oldOne.getPropertyDescriptionList();
        List<PropertyDescription> currentPropertyDescriptionList = newOne.getPropertyDescriptionList();
        List<PropertyDescription> removePropertyList = new ArrayList<PropertyDescription>();
        List<PropertyDescription> addPropertyList = new ArrayList<PropertyDescription>(
                currentPropertyDescriptionList);
        Map<PropertyDescription, PropertyDescription> pdMap = new HashMap<PropertyDescription, PropertyDescription>();
        for (PropertyDescription pd1 : oldPropertyDescriptionList) {
            boolean remove = true;
            for (PropertyDescription pd2 : currentPropertyDescriptionList) {
                if (pd1.getId().equals(pd2.getId())) {
                    addPropertyList.remove(pd2);
                    if (!pd1.equals(pd2)) {
                        pdMap.put(pd2, pd1);
                    }
                    remove = false;
                    break;
                }
            }
            if (remove) {
                removePropertyList.add(pd1);
            }
        }

        Iterator<Table> tableIter = cfg.getTableMappings();
        while (tableIter.hasNext()) {
            Table table = tableIter.next();
            TableMetadata tableInfo = meta.getTableMetadata(table.getName(),
                    (table.getSchema() == null) ? defaultSchema : table.getSchema(),
                    (table.getCatalog() == null) ? defaultCatalog : table.getCatalog(), table.isQuoted()

            );
            if (tableInfo == null) {
                alterSqls.add(table.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
            } else {
                if (!table.getName().equalsIgnoreCase(newOne.getName())) {
                    continue;
                }
                for (PropertyDescription removeProperty : removePropertyList) {
                    if (removeProperty.getControl().isSupportMutil()
                            && removeProperty.getControl().isDynamic()) {
                        alterSqls.add("drop table " + dialect.openQuote() + newOne.getName().toUpperCase() + "_"
                                + removeProperty.getName().toUpperCase() + "_RELATION" + dialect.closeQuote());
                    } else {
                        if (((DialectExtention) dialect).needDropForeignKeyBeforeDropColumn()) {
                            ForeignKeyMetadata fkm = tableInfo.getForeignKeyMetadataByColumnNames(
                                    new String[] { removeProperty.getName().toUpperCase() });
                            if (fkm != null) {
                                alterSqls.add("alter table " + dialect.openQuote()
                                        + newOne.getName().toUpperCase() + dialect.closeQuote() + " "
                                        + dialect.getDropForeignKeyString() + " " + dialect.openQuote()
                                        + fkm.getName() + dialect.closeQuote());
                            }
                        }
                        alterSqls.add("alter table " + dialect.openQuote() + newOne.getName().toUpperCase()
                                + dialect.closeQuote() + " drop column " + dialect.openQuote()
                                + removeProperty.getName().toUpperCase() + dialect.closeQuote());
                    }
                }
                StringBuffer root = new StringBuffer("alter table ")
                        .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema)).append(' ')
                        .append(dialect.getAddColumnString());
                Iterator<Column> iter = table.getColumnIterator();
                while (iter.hasNext()) {
                    Column column = iter.next();
                    PropertyDescription pd = null;
                    if ((pd = contains(column.getName(), addPropertyList)) != null) {
                        StringBuffer alter = new StringBuffer(root.toString()).append(' ')
                                .append(column.getQuotedName(dialect)).append(' ')
                                .append(column.getSqlType(dialect, mapping));

                        String defaultValue = column.getDefaultValue();
                        if (defaultValue != null) {
                            alter.append(" default ").append(defaultValue);

                            if (column.isNullable()) {
                                alter.append(dialect.getNullColumnString());
                            } else {
                                alter.append(" not null");
                            }

                        }

                        boolean useUniqueConstraint = column.isUnique() && dialect.supportsUnique()
                                && (!column.isNullable() || dialect.supportsNotNullUnique());
                        if (useUniqueConstraint) {
                            alter.append(" unique");
                        }

                        if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) {
                            alter.append(" check(").append(column.getCheckConstraint()).append(")");
                        }

                        String columnComment = column.getComment();
                        if (columnComment != null) {
                            alter.append(dialect.getColumnComment(columnComment));
                        }

                        alterSqls.add(alter.toString());
                    } else if ((pd = contains(column.getName(), pdMap)) != null) {
                        PropertyDescription newPd = pd;
                        PropertyDescription oldPd = pdMap.get(pd);
                        if (!oldPd.getName().equalsIgnoreCase(newPd.getName())) {
                            StringBuffer renameColumn = new StringBuffer("alter table ")
                                    .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
                                    .append(' ').append(((DialectExtention) dialect).getRenameColumnString(
                                            oldPd.getName().toUpperCase(), newPd.getName().toUpperCase()));
                            if (((DialectExtention) dialect).isAddColumnDefinitionWhenRename()) {
                                renameColumn.append(" ");
                                renameColumn.append(column.getSqlType(dialect, mapping));
                            }
                            executeSql(conn, renameColumn.toString());
                        }

                        StringBuffer alterColumn = new StringBuffer("alter table ")
                                .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
                                .append(' ').append(((DialectExtention) dialect).getModifyColumnString(column))
                                .append(' ').append(column.getQuotedName(dialect));
                        alterColumn.append(" ");
                        alterColumn.append(column.getSqlType(dialect, mapping));
                        String defaultValue = column.getDefaultValue();
                        if (defaultValue != null) {
                            alterColumn.append(" default ").append(defaultValue);

                            if (column.isNullable()) {
                                alterColumn.append(dialect.getNullColumnString());
                            } else {
                                alterColumn.append(" not null");
                            }

                        }

                        boolean useUniqueConstraint = column.isUnique() && dialect.supportsUnique()
                                && (!column.isNullable() || dialect.supportsNotNullUnique());
                        if (useUniqueConstraint) {
                            alterColumn.append(" unique");
                        }

                        if (column.hasCheckConstraint() && dialect.supportsColumnCheck()) {
                            alterColumn.append(" check(").append(column.getCheckConstraint()).append(")");
                        }

                        String columnComment = column.getComment();
                        if (columnComment != null) {
                            alterColumn.append(dialect.getColumnComment(columnComment));
                        }
                        alterSqls.add(alterColumn.toString());
                    }
                }
            }
        }
        tableIter = cfg.getTableMappings();
        while (tableIter.hasNext()) {
            Table table = tableIter.next();
            Iterator<ForeignKey> subIter = table.getForeignKeyIterator();
            while (subIter.hasNext()) {
                ForeignKey fk = (ForeignKey) subIter.next();
                if (fk.isPhysicalConstraint()) {
                    TableMetadata tableInfo = meta.getTableMetadata(table.getName(),
                            (table.getSchema() == null) ? defaultSchema : table.getSchema(),
                            (table.getCatalog() == null) ? defaultCatalog : table.getCatalog(), table.isQuoted()

                    );
                    if (tableInfo == null) {
                        String[] cols = new String[fk.getColumnSpan()];
                        String[] refcols = new String[fk.getColumnSpan()];
                        int i = 0;
                        Iterator<Column> refiter = null;
                        if (fk.isReferenceToPrimaryKey()) {
                            refiter = fk.getReferencedTable().getPrimaryKey().getColumnIterator();
                        } else {
                            refiter = fk.getReferencedColumns().iterator();
                        }

                        Iterator<Column> columnIter = fk.getColumnIterator();
                        while (columnIter.hasNext()) {
                            cols[i] = ((Column) columnIter.next()).getQuotedName(dialect);
                            refcols[i] = ((Column) refiter.next()).getQuotedName(dialect);
                            i++;
                        }
                        String result = dialect
                                .getAddForeignKeyConstraintString(
                                        fk.getName(), cols, fk.getReferencedTable().getQualifiedName(dialect,
                                                defaultCatalog, defaultSchema),
                                        refcols, fk.isReferenceToPrimaryKey());
                        StringBuffer createFK = new StringBuffer("alter table ")
                                .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
                                .append(dialect.supportsCascadeDelete() ? result + " on delete cascade"
                                        : result);
                        alterSqls.add(createFK.toString());
                    }
                }
            }
        }
        this.executeSqls(conn, alterSqls);
    } catch (Exception e) {
        throw new PlutoException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }
}

From source file:com.clican.pluto.orm.dynamic.impl.DataBaseOperationImpl.java

License:LGPL

@SuppressWarnings("unchecked")
public void createTable(Configuration cfg) {
    Connection conn = null;/*w  w w  . ja v  a2s  .co m*/
    DatabaseMetadata meta = null;
    String defaultCatalog = cfg.getProperties().getProperty(Environment.DEFAULT_CATALOG);
    String defaultSchema = cfg.getProperties().getProperty(Environment.DEFAULT_SCHEMA);
    List<String> createSqls = new ArrayList<String>();
    try {
        conn = dataSource.getConnection();
        meta = new DatabaseMetadata(conn, dialect);
        Iterator<Table> tableIter = cfg.getTableMappings();
        Mapping mapping = cfg.buildMapping();
        while (tableIter.hasNext()) {
            Table table = (Table) tableIter.next();
            TableMetadata tableInfo = meta.getTableMetadata(table.getName(),
                    (table.getSchema() == null) ? defaultSchema : table.getSchema(),
                    (table.getCatalog() == null) ? defaultCatalog : table.getCatalog(), table.isQuoted()

            );
            if (tableInfo == null) {
                createSqls.add(table.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
            }
        }
        tableIter = cfg.getTableMappings();
        while (tableIter.hasNext()) {
            Table table = (Table) tableIter.next();
            Iterator<ForeignKey> subIter = table.getForeignKeyIterator();
            while (subIter.hasNext()) {
                ForeignKey fk = (ForeignKey) subIter.next();
                if (fk.isPhysicalConstraint()) {
                    TableMetadata tableInfo = meta.getTableMetadata(table.getName(),
                            (table.getSchema() == null) ? defaultSchema : table.getSchema(),
                            (table.getCatalog() == null) ? defaultCatalog : table.getCatalog(), table.isQuoted()

                    );
                    if (tableInfo == null) {
                        String[] cols = new String[fk.getColumnSpan()];
                        String[] refcols = new String[fk.getColumnSpan()];
                        int i = 0;
                        Iterator<Column> refiter = null;
                        if (fk.isReferenceToPrimaryKey()) {
                            refiter = fk.getReferencedTable().getPrimaryKey().getColumnIterator();
                        } else {
                            refiter = fk.getReferencedColumns().iterator();
                        }

                        Iterator<Column> columnIter = fk.getColumnIterator();
                        while (columnIter.hasNext()) {
                            cols[i] = ((Column) columnIter.next()).getQuotedName(dialect);
                            refcols[i] = ((Column) refiter.next()).getQuotedName(dialect);
                            i++;
                        }
                        String result = dialect
                                .getAddForeignKeyConstraintString(
                                        fk.getName(), cols, fk.getReferencedTable().getQualifiedName(dialect,
                                                defaultCatalog, defaultSchema),
                                        refcols, fk.isReferenceToPrimaryKey());
                        StringBuffer createFK = new StringBuffer("alter table ")
                                .append(table.getQualifiedName(dialect, defaultCatalog, defaultSchema))
                                .append(dialect.supportsCascadeDelete() ? result + " on delete cascade"
                                        : result);
                        createSqls.add(createFK.toString());
                    }
                }
            }
        }
        this.executeSqls(conn, createSqls);
    } catch (DDLException e) {
        throw e;
    } catch (Exception e) {
        throw new PlutoException(e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }

}

From source file:com.co.codesoftware.persistencia.configuracion.HibernateUtil.java

private static SessionFactory buildSessionFactory() {
    try {/*from ww w .  j  a  v  a  2 s  . co m*/
        if (sessionFactory == null) {
            config = "/hibernate.cfg.xml";
            Configuration configuration = new Configuration()
                    .configure(HibernateUtil.class.getResource("/hibernate.cfg.xml"));
            StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
            serviceRegistryBuilder.applySettings(configuration.getProperties());
            ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
        return sessionFactory;
    } catch (Throwable ex) {
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

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();//  ww w  .  j  a va2  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();
}