Example usage for org.hibernate.cfg Configuration buildSessionFactory

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

Introduction

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

Prototype

public SessionFactory buildSessionFactory() throws HibernateException 

Source Link

Document

Create a SessionFactory using the properties and mappings in this configuration.

Usage

From source file:controller.InsertSubjects.java

public static void main(String[] args) {
    //configure cfg xml file
    Configuration cf = new Configuration();
    cf.configure("xmlFiles/hibernate.cfg.xml");

    //build session factory
    SessionFactory sf = cf.buildSessionFactory();
    //get session object
    Session session = sf.openSession();/*from  w  ww  . j a va 2  s . c  om*/
    //get Transaction object
    Transaction tr = session.beginTransaction();

    //SUBJECTS OF CS
    //          Subjects subjects = new Subjects();
    //          subjects.setDepartment("comptuer system");
    //          subjects.setSemester("1st");
    //          subjects.setSubjectName("Calculus");
    //        //INSERT ATTENDANCE OBJECT
    //        session.save(subjects);
    //        tr.commit();
    //        session.evict(subjects);
    //close session and session factory
    session.close();
    sf.close();

}

From source file:controller2.Driver.java

public static void main(String[] args) {
    //DepartAndBatches table object
    DepartAndBatches db = new DepartAndBatches();
    db.setDepart("CS");
    db.setBatch("17");

    //StudetPersonalInfo table object
    StudentPersonalInfo pInfo = new StudentPersonalInfo();
    pInfo.setBatch("13");
    pInfo.setRollNum("13_CS_19");
    pInfo.setName("imtiaz");
    pInfo.setCnic("44205-82187913");
    pInfo.setFatherName("Sobdar wassan");
    pInfo.setFtContactNum("+923333945719");
    pInfo.setStContactNum("+923002639694");
    pInfo.setGender("Male");
    pInfo.setCaste("wassan");
    pInfo.setTempAdd("Mallir cantt karachi");
    pInfo.setPermAdd("Village Gujh Heran Taulka Sinjhoro District Sanghar");
    pInfo.setStEmail("wassanimtiaz@outlook.com");
    pInfo.setPassword("pakistan");
    pInfo.setBatch("13");
    //Master table object
    Master m = new Master();
    m.setDepart("civil");
    m.setMasterKey("civil");

    //                Master m = new Master();
    //                m.setDepart("Computer");
    //                m.setMasterKey("imtiaz");
    try {/*from  w  w  w  .  j a v a2s  .  c  om*/

        Configuration cf = new Configuration();
        cf.configure("xmlFiles/hibernate.cfg.xml");
        SessionFactory sf = cf.buildSessionFactory();
        // SessionFactory sf = HibernateUtil.getSessionFactory();
        Session ses = sf.openSession();
        ses.save(pInfo);
        ses.beginTransaction().commit();
        ses.evict(pInfo);

        // ses = sf.openSession();
        //                ses.save(pInfo);
        //                ses.beginTransaction().commit();
        pInfo = (StudentPersonalInfo) ses.get(StudentPersonalInfo.class, "13_CS_19");
        System.out.println(pInfo.getRollNum());
        System.out.println(pInfo.getName());

        //                ses.evict(m);
        //                ses.close(); 

        m = (Master) ses.get(Master.class, "cs");
        System.out.println(m.getDepart());
        System.out.println(m.getMasterKey());
        //                ses = sf.openSession();
        //                ses.save(db);
        //                ses.beginTransaction().commit();
        //                ses.evict(db);
        //                ses.close();
        // ses = sf.openSession();
        // m = (Student)ses.get(Student.class, 1);
        // System.out.println("Name="+m.getName());
        //                System.out.println("Id="+m.getId());

        ses.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:csvToSQLite3.PojoListToDB.java

public PojoListToDB(ArrayList<PojoUntil2005> listOfPojo, String NameOfCfgFile) {
    this.listOfPojo = listOfPojo;
    /*/*  w  w w.j a  va 2 s . c om*/
    HIbernate ??????????????????
    ?props ???????
    ?????hibernate5.1. ?????????
    PersistenceProvider provider = new HibernatePersistenceProvider();
    EntityManagerFactory emf = provider.createEntityManagerFactory(PERSISTENCE_UNIT, props);
    */

    Configuration cfg = new Configuration().configure(new File(NameOfCfgFile));
    sessionFactory = cfg.buildSessionFactory();
    session = sessionFactory.openSession();
    transaction = session.getTransaction();

    /*
    EntityManagerFactory fac = Persistence.createEntityManagerFactory(NameOfEntityManager, createProps());
    em = fac.createEntityManager();
    tx = em.getTransaction();
    */

    System.out.println("DEBUG:PojoListToDB:" + listOfPojo.size());
}

From source file:cz.jirutka.rsql.hibernate.SessionFactoryInitializer.java

License:Open Source License

public static SessionFactory getSessionFactory() {
    if (instance != null)
        return instance;

    Configuration configuration = new Configuration();
    configuration.setProperty(Environment.DRIVER, "org.hsqldb.jdbcDriver");
    configuration.setProperty(Environment.URL, "jdbc:hsqldb:mem:ProductDAOTest");
    configuration.setProperty(Environment.USER, "sa");
    configuration.setProperty(Environment.DIALECT, HSQLDialect.class.getName());
    configuration.setProperty(Environment.SHOW_SQL, "true");
    configuration.addAnnotatedClass(Course.class);
    configuration.addAnnotatedClass(Department.class);
    configuration.addAnnotatedClass(Person.class);

    instance = configuration.buildSessionFactory();

    return instance;
}

From source file:db.SessionCreator.java

public static Session getSession() {
    Configuration configuration = new Configuration();
    configuration.configure();/* w w  w.j  av a2s .  c  om*/
    SessionFactory factory = configuration.buildSessionFactory();
    Session session = factory.openSession();
    return session;
}

From source file:de.arago.data.util.ConfigHelper.java

License:Open Source License

static SessionFactory makeFactory(String datasource, Properties p) {
    final Configuration configuration = new Configuration();
    configuration.configure();/*w  ww  . jav a 2s  . c om*/

    String jdbcUrl = System.getProperty(PREFIX + datasource);

    if (jdbcUrl == null || jdbcUrl.isEmpty()) {
        jdbcUrl = "jdbc:mysql://127.0.0.1/rike?user=rike&password=rike&useUnicode=true&characterEncoding=UTF-8";
    }

    configuration.setProperty("hibernate.connection.url", jdbcUrl);
    setCredentials(configuration, jdbcUrl);

    setDebug(configuration);
    setAdditionalProperties(configuration, p);

    return configuration.buildSessionFactory();
}

From source file:de.berlios.jfindmyfiles.catalog.CatalogEngine.java

License:Open Source License

private void recreateConnection(String dbname, String dburl, String port, String username, String password,
        int dbType, boolean open) {

    closeCatalog();/*from  www.j a v a2s .c o m*/

    String strategy = "create";
    try {
        Configuration hConfig = new Configuration()
                .configure("de/berlios" + "/jfindmyfiles/catalog/hibernate.general.cfg.xml");

        if (open) {
            strategy = "update";
        }
        //Creation strategy
        hConfig.setProperty("hibernate.hbm2ddl.auto", strategy);

        switch (dbType) {
        case CatalogConstants.FIREBIRD://TODO: change for FIREBIRD database engine

            hConfig.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
            hConfig.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
            hConfig.setProperty("hibernate.connection.url", "jdbc:hsqldb:file:" + dburl + "/" + dbname);
            hConfig.setProperty("hibernate.connection.username", "sa");
            hConfig.setProperty("hibernate.connection.password", password);
            hConfig.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

            break;
        case CatalogConstants.POSTGRESQL://TODO: change for POSTGRESQL database engine

            hConfig.setProperty("hibernate.dialect", "");
            hConfig.setProperty("hibernate.connection.driver_class", "");
            hConfig.setProperty("hibernate.connection.url", "");
            hConfig.setProperty("hibernate.connection.username", "");
            hConfig.setProperty("hibernate.connection.password", password);

            break;
        case CatalogConstants.MYSQL:
            hConfig.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
            hConfig.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
            hConfig.setProperty("hibernate.connection.url",
                    "jdbc:mysql://" + dburl + ":" + port + "/" + dbname);
            hConfig.setProperty("hibernate.connection.username", username);
            hConfig.setProperty("hibernate.connection.password", password);
            break;
        case CatalogConstants.MSSQL://TODO: change for MSSQL database engine

            hConfig.setProperty("hibernate.dialect", "");
            hConfig.setProperty("hibernate.connection.driver_class", "");
            hConfig.setProperty("hibernate.connection.url", "");
            hConfig.setProperty("hibernate.connection.username", "");
            hConfig.setProperty("hibernate.connection.password", password);
            break;
        default://If it's not a network database we can only use HSQLDB engine

            hConfig.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
            hConfig.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
            hConfig.setProperty("hibernate.connection.url", "jdbc:hsqldb:file:" + dburl + "/" + dbname);
            hConfig.setProperty("hibernate.connection.username", "sa");//Default user for every HSQLDB database

            //Try to shutdown the database as soon as there all connections are gone
            //hConfig.setProperty("hibernate.connection.shutdown", "true");

            //NOTE:TODO: remove this line, only for debugging what seems to be HSQLDB related bug.
            hConfig.setProperty("hibernate.jdbc.batch_size", "0");

            hConfig.setProperty("hibernate.connection.password", "");//HSQLDB has a user with no password

        }

        sessionFactory = hConfig.buildSessionFactory();
        opened = true;
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "HIBERNATE: Initial SessionFactory creation failed.", ex);
        opened = false;
        throw new ExceptionInInitializerError(ex);
    }

}

From source file:de.cosmocode.palava.jpa.hibernate.DefaultHibernateService.java

License:Apache License

@Override
public void initialize() {
    final Configuration configuration = new AnnotationConfiguration();

    LOG.debug("Adding hibernate schema: {}", schema);
    configuration.addURL(schema);/*from   ww  w  .j  a va2  s  .c o  m*/

    LOG.debug("Adding hibernate config file: {}", config);
    configuration.configure(config);

    if (interceptor == null) {
        LOG.info("No interceptor configured");
    } else {
        LOG.info("Using {} as interceptor", interceptor);
        configuration.setInterceptor(interceptor);
    }

    if (propagateEvents) {
        LOG.info("Registering event listeners");
        for (Entry<String, Class<?>> entry : LISTENERS.entrySet()) {
            final String event = entry.getKey();
            final Class<?> type = entry.getValue();
            final Key<?> key = Key.get(type, event);
            final Object listener = registry.proxy(key);
            LOG.info("Registering {} for {}", listener, event);
            configuration.setListener(event, listener);
        }
    } else {
        LOG.info("Events are not propagated through the registry");
    }

    LOG.debug("Building session factory");
    this.factory = configuration.buildSessionFactory();

    statistics.setSessionFactory(factory);
    statistics.setStatisticsEnabled(true);
    mBeanService.register(statistics, "name", name);
}

From source file:de.decidr.model.testing.LowLevelDatabaseTest.java

License:Apache License

@BeforeClass
public static final void setUpClass() {
    Configuration config = new Configuration();
    config.configure("/hibernate.cfg.xml");
    /*//from   w  w  w.j a v  a 2  s.  co  m
     * Minimize concurrency issues.
     */
    config.setProperty("hibernate.connection.isolation",
            Integer.toString(Connection.TRANSACTION_READ_UNCOMMITTED));
    config.setProperty("hibernate.connection.autocommit", "true");
    session = config.buildSessionFactory().openSession();
}

From source file:de.decidr.test.database.main.TestDataGenerator.java

License:Apache License

/**
 * Applies the current application settings.
 *///  w  w  w .  j  a va2s .c  o m
private void applyCurrentSettings() {
    String connectionUrl = settings.getProperty(PROPERTY_CONNECTION_URL);
    Configuration config = new Configuration().configure();
    config.setProperty("hibernate.connection.url", connectionUrl);

    tc = HibernateTransactionCoordinator.create(config.buildSessionFactory());
}