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

public Configuration configure() throws HibernateException 

Source Link

Document

Use the mappings and properties specified in an application resource named hibernate.cfg.xml.

Usage

From source file:CrosswordTestBase.java

public static SessionFactory buildSessionFactory() {
    Configuration config = new Configuration();
    config.configure();
    StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
    ssrb.applySettings(config.getProperties());
    StandardServiceRegistry ssr = ssrb.build();
    return config.buildSessionFactory(ssr);
}

From source file:Storage.java

License:Open Source License

/**
 * Creates a new SessionFactory instance
 *//*from   ww w .  j  a v a2s  . c  o  m*/
public static void initialize() {
    if (factory == null) {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
            factory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
}

From source file:GetMovDetails.java

protected int getDetails(String movname) {
    Configuration configuration = new Configuration();
    configuration.configure();
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    Session session = new Configuration().configure().buildSessionFactory(serviceRegistry).openSession();

    Transaction tx = null;// w w  w  .j a v  a 2s.co m
    try {
        tx = session.beginTransaction();
        String hql = "FROM GS_Movie m where m.name=:movname";
        Query query = session.createQuery(hql);
        query.setParameter("movname", movname);
        List results = query.list();
        GS_Movie gS_Movie = (GS_Movie) results.iterator().next();
        name = gS_Movie.getName();
        movid = gS_Movie.getMovid();
        plot = gS_Movie.getPlot();
        year = String.valueOf(gS_Movie.getYear());
        dir = gS_Movie.getDirector();
        genre = gS_Movie.getGenre();
        prod = gS_Movie.getProducer();
        cast = gS_Movie.getCast();
        //Update mov details
        System.out.println(name);
        System.out.println(movid);
        System.out.println(plot);
        System.out.println(year);
        System.out.println(dir);
        System.out.println(genre);
        System.out.println(prod);
        System.out.println(cast);

        result = 1;

    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        session.close();
        return result;
    }
}

From source file:saajResponse.java

private void saveEmployee(Employee e) {
    Configuration cfg = new Configuration();
    SessionFactory sessionFactory = cfg.configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.save(e);//ww  w .  j  a v a  2s.co m
    session.beginTransaction();
    session.persist(e);
    session.getTransaction().commit();
    System.out.println("Emplyoee saved");
}

From source file:abid.password.wicket.GuiceModule.java

License:Apache License

@Override
protected void configure() {
    install(PersistenceService.usingHibernate().across(UnitOfWork.REQUEST).buildModule());

    Configuration configuration = new Configuration();
    configuration.configure();

    bind(Configuration.class).toInstance(configuration);
    bind(UserService.class).to(UserServiceImpl.class);
    bind(UserDao.class).to(UserDaoHibernateImpl.class);
    bind(WebApplication.class).to(MutablePasswordApplication.class);
}

From source file:abstractDao.HibernateFactory.java

/**
 *
 * @return @throws HibernateException/*  w w w.ja  v  a  2 s.c om*/
 */
private static SessionFactory configureSessionFactory() throws HibernateException {
    Configuration configuration = new AnnotationConfiguration();
    configuration.configure();
    sessionFactory = configuration.buildSessionFactory();
    return sessionFactory;
}

From source file:Application.UI.java

private static SessionFactory configureSessionFactory() throws HibernateException {
    Configuration configuration = new Configuration();
    configuration.configure();

    Properties properties = configuration.getProperties();

    serviceRegistry = new ServiceRegistryBuilder().applySettings(properties).buildServiceRegistry();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    return sessionFactory;
}

From source file:at.treedb.db.hibernate.DAOhibernate.java

License:Open Source License

/**
 * Creates an instance of a Hibernate DAO.
 * /*from  w  ww  .j  a v  a2 s.c o  m*/
 * @param database
 *            database
 * @param dbURL
 *            database URL
 * @param dbUser
 *            database User
 * @param dbPWD
 *            database password
 * @return {@code DAOhibernate} object
 * @throws Exception
 */
public static synchronized DAOhibernate getInstance(DAO.DB database, DDL_STRATEGY dll, String dbURL,
        String dbUser, String dbPWD, PERSISTENCE_CFG_CREATE_STRATEGY creationStrategy) throws Exception {
    if (instance == null) {
        if (dbPWD == null) {
            dbPWD = "";
        }
        String hibernateDialect = null;
        String dbDriver = null;
        if (database == null) {
            throw new Exception("DAOhibernate.getInstance(): Database must be set!");
        }
        switch (database) {
        case H2:
            dbDriver = "org.h2.Driver";
            hibernateDialect = "H2Dialect";
            break;
        case DERBY:
            if (dbURL.contains("jdbc:derby://")) {
                dbDriver = "org.apache.derby.jdbc.ClientDriver";
            } else {
                dbDriver = "org.apache.derby.jdbc.EmbeddedDriver";
            }
            hibernateDialect = "DerbyTenSevenDialect";
            break;
        case HSQLDB:
            dbDriver = "org.hsqldb.jdbc.JDBCDriver";
            hibernateDialect = "HSQLDialect";
            break;
        case MYSQL:
            dbDriver = "com.mysql.jdbc.Driver";
            hibernateDialect = "MySQLDialect";
            break;
        case MARIADB:
            dbDriver = "org.mariadb.jdbc.Driver";
            hibernateDialect = "MySQLDialect";
            break;
        case POSTGRES:
            dbDriver = "org.postgresql.Driver";
            hibernateDialect = "PostgreSQLDialect";
            break;
        case SQLSERVER:
            dbDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
            hibernateDialect = "SQLServerDialect";
            break;
        case ORACLE:
            dbDriver = "oracle.jdbc.OracleDriver";
            hibernateDialect = "Oracle10gDialect";
            break;
        case FIREBIRD:
            dbDriver = "org.firebirdsql.jdbc.FBDriver";
            hibernateDialect = "FirebirdDialect";
            break;
        case DB2:
            dbDriver = "com.ibm.db2.jcc.DB2Driver";
            hibernateDialect = "DB2Dialect";
            break;
        case SQLITE:
            dbDriver = "org.sqlite.JDBC";
            hibernateDialect = "SQLiteDialect";
            break;
        default:
            throw new Exception("Missing DB implementation for" + database);
        }
        String hbm2ddl = "none";
        switch (dll) {
        case VALIDATE:
            hbm2ddl = "validate";
            break;
        case UPDATE:
            hbm2ddl = "update";
            break;
        case CREATE:
            hbm2ddl = "create";
            break;

        }
        ReplaceText[] rt = new ReplaceText[] { new ReplaceText("creationDate", (new Date()).toString()),
                new ReplaceText("hbm2ddl", hbm2ddl), new ReplaceText("dbDriver", dbDriver),
                new ReplaceText("dbURL", dbURL), new ReplaceText("dialect", hibernateDialect),
                new ReplaceText("dbUser", dbUser), new ReplaceText("dbPwd", dbPWD), };

        URI hibernateCfg = DAOhibernate.class.getResource("/hibernateTemplate.cfg.xml").toURI();

        String cfgStr = new String(
                Stream.readInputStream(DAOhibernate.class.getResourceAsStream("/hibernateTemplate.cfg.xml")));

        String xml = ReplaceText.replaceText(cfgStr, rt);
        String path = hibernateCfg.toString();
        int skip = 0;
        boolean jar = false;
        if (path.startsWith("file:")) {
            skip = "file:".length();
        } else if (path.startsWith("jar:file:")) {
            skip = "jar:file:".length();
            jar = true;
        }
        path = path.replace("%20", " ");
        path = path.substring(skip);
        path = path.substring(0, path.lastIndexOf("/")) + "/hibernateTemplate.cfg";

        if (jar) {
            path = path.substring(0, path.indexOf("WEB-INF"));

            String tomcat = path + "WEB-INF/classes/META-INF/";
            new File(tomcat).mkdirs();
            Stream.writeString(new File(tomcat + "hibernateTemplate.cfg"), xml);
            path += "hibernateTemplate.cfg";
        }

        Configuration cfg = new Configuration();
        if (creationStrategy == PERSISTENCE_CFG_CREATE_STRATEGY.NO_FILE_CREATION) {
            cfg.configure();
        } else if (creationStrategy == PERSISTENCE_CFG_CREATE_STRATEGY.DEFAULT_LOCATION) {
            File file = new File(path);
            Stream.writeString(file, xml);
            cfg.configure(file);
        } else {
            File tmpFile = File.createTempFile("hibernateTemplate", ".cfg");
            Stream.writeString(tmpFile, xml);
            cfg.configure(tmpFile);
        }

        @SuppressWarnings("rawtypes")
        ArrayList<Class> annotations = null;
        annotations = loadEnitiyClasses(DBentities.getClassesAsList(), cfg);
        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
        sessionFactory = cfg.buildSessionFactory(serviceRegistry);

        instance = new DAOhibernate(database);
        instance.setConfiguration(cfg);
        DAOhibernate.annotatedClasses = annotations;

        instance.beginTransaction();
        instance.getActualSession().doWork(new Work() {
            @Override
            public void execute(Connection connection) throws SQLException {
                databaseName = connection.getMetaData().getDatabaseProductName();
                databaseVersion = connection.getMetaData().getDatabaseProductVersion();
            }
        });
        instance.endTransaction();

    }
    return instance;
}

From source file:banco.GeraBanco.java

public static void main(String[] args) {
    try {/*  w w w.j av a  2s . c o  m*/
        Configuration cfg = new Configuration();
        cfg.configure();
        SchemaExport se = new SchemaExport(cfg);
        se.create(true, true);
        JOptionPane.showMessageDialog(null, "O Banco de Dados foi gerado com sucesso!", "Fafica .:. Alerta",
                JOptionPane.INFORMATION_MESSAGE);
    } catch (HibernateException | HeadlessException e) {
        System.out.println(e);
        JOptionPane.showMessageDialog(null, "Erro ao Gerar a Base de Dados!", "Fafica .:. Alerta",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:bd.ac.seu.labexam.SessionFactorySingleton.java

private SessionFactorySingleton() {
    Configuration configuration = new Configuration();
    configuration.configure();
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}