Example usage for org.hibernate.cfg Configuration Configuration

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

Introduction

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

Prototype

public Configuration() 

Source Link

Usage

From source file:com.autobizlogic.abl.logic.dynamic.Deployer.java

License:Open Source License

/**
 * Deploy a jar into a database for use by DatabaseClassManager.
 * @param props Should contain the required parameters:
 * <ul>//from   ww w  . jav  a 2  s.c  o m
 * <li>either HIB_CFG_FILE (Hibernate config file path as a string) or 
 * HIB_CFG as a Hibernate Configuration object
 * <li>PROJECT_NAME: the name of the project to deploy to (will be created if it does not exist)
 * <li>JAR_FILE_NAME: the path of the jar file to deploy, as a String
 * <li>EFFECTIVE_DATE: the date/time at which the new logic classes should take effect, 
 * as a java.util.Date (optional)
 * </ul>
 * @return Null if everything went OK, otherwise a reason for the failure
 */
public static String deploy(Properties props) {

    Logger root = Logger.getRootLogger();
    root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
    Logger.getLogger("org.hibernate").setLevel(Level.WARN);
    Logger.getLogger("org.hibernate.tool.hbm2ddl").setLevel(Level.DEBUG);
    Logger.getLogger("org.hibernate.SQL").setLevel(Level.DEBUG);
    Logger.getLogger("org.hibernate.transaction").setLevel(Level.DEBUG);

    Configuration config;
    if (props.get(HIB_CFG) == null) {
        config = new Configuration();
        File cfgFile = new File((String) props.get(HIB_CFG_FILE));
        config.configure(cfgFile);
    } else
        config = (Configuration) props.get(HIB_CFG);

    if (config.getClassMapping(Project.class.getName()) == null) {
        config.addAnnotatedClass(Project.class);
        config.addAnnotatedClass(LogicFile.class);
        config.addAnnotatedClass(LogicFileLog.class);
    }

    SessionFactory sessFact = config.buildSessionFactory();
    Session session = sessFact.getCurrentSession();
    Transaction tx = session.beginTransaction();

    Query query = session.createQuery("from Project where name = :name").setString("name",
            (String) props.get(PROJECT_NAME));
    Project project = (Project) query.uniqueResult();
    if (project == null) {
        project = new Project();
        project.setName((String) props.get(PROJECT_NAME));
        session.save(project);
    }

    LogicFile logicFile = new LogicFile();
    String fileName = (String) props.get(JAR_FILE_NAME);
    String shortFileName = fileName;
    if (fileName.length() > 300)
        shortFileName = fileName.substring(0, 300);
    logicFile.setName(shortFileName);
    logicFile.setCreationDate(new Timestamp(System.currentTimeMillis()));
    File jarFile = new File((String) props.get(JAR_FILE_NAME));
    try {
        FileInputStream inStr = new FileInputStream(fileName);
        Blob blob = session.getLobHelper().createBlob(inStr, jarFile.length());
        logicFile.setContent(blob);
    } catch (Exception ex) {
        throw new RuntimeException("Error while storing jar file into database", ex);
    }
    Date effDate = (Date) props.get(EFFECTIVE_DATE);
    logicFile.setEffectiveDate(new Timestamp(effDate.getTime()));
    logicFile.setProject(project);
    session.save(logicFile);

    tx.commit();
    sessFact.close();

    return null;
}

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();/*from   w w w.  j a  v  a  2s  . co  m*/

    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  w w  w. j  a v a 2s .  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.belajar.ORMHibernate.Main.MainHibernate.java

public static void main(String[] args) {
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

    Person p = new Person();
    p.setName("Shinta");
    p.setPassword("diditshinta");
    System.out.print("saved!");

    Session session = sessionFactory.openSession();
    try {/*from  w  w  w  . j  ava 2s  .  c o  m*/
        session.beginTransaction();
        session.save(p);
        session.getTransaction().commit();
    } catch (HibernateException hibernateException) {
        session.getTransaction().rollback();
    }
    session.close();

    session = sessionFactory.openSession();
    Query query = session.createQuery("from Person");
    List<Person> persons = query.list();
    for (Person person : persons) {
        System.out.println("Id: " + person.getId());
        System.out.println("Name: " + person.getName());
        System.out.println("Password: " + person.getPassword() + "\n");
    }

    session.close();
    sessionFactory.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  . j  av a  2  s  . com*/
                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.bloatit.data.SessionManager.java

License:Open Source License

/**
 * Create the configuration for hibernate sessionFactory. Handle the
 * encryptor to encrypt the db password in the hibernate.cfg.xml conf file.
 * /*from w  w w .ja va2 s.  c  o  m*/
 * @return
 */
private static Configuration createConfiguration() {
    final HibernatePBEEncryptorRegistry registry = HibernatePBEEncryptorRegistry.getInstance();
    registry.registerPBEStringEncryptor("strongHibernateStringEncryptor", ConfigurationManager.getEncryptor());
    final Configuration configuration = new Configuration().configure();
    return configuration;
}

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

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

    configuration.configure();/*w  w  w  . ja v a 2 s .  c  o  m*/

    StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();

    serviceRegistryBuilder.applySettings(configuration.getProperties());

    serviceRegistry = serviceRegistryBuilder.build();

    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    return sessionFactory;
}

From source file:com.brienwheeler.apps.schematool.SchemaToolBean.java

License:Open Source License

private Configuration determineHibernateConfiguration()
        throws MappingException, ClassNotFoundException, IOException {
    // Read in the bean definitions but don't go creating all the singletons,
    // because that causes creation of data sources and connections to database, etc.
    NonInitializingClassPathXmlApplicationContext context = new NonInitializingClassPathXmlApplicationContext(
            new String[] { emfContextLocation });
    try {//from   www.  j a  v  a2 s.c  o  m
        context.loadBeanDefinitions();

        // Get well-known EntityManagerFactory bean definition by name
        BeanDefinition emfBeanDef = context.getBeanDefinition(emfContextBeanName);
        if (emfBeanDef == null) {
            throw new RuntimeException("no bean defined: " + emfContextBeanName);
        }

        // Get the name of the persistence unit for this EntityManagerFactory
        PropertyValue puNameProperty = emfBeanDef.getPropertyValues().getPropertyValue("persistenceUnitName");
        if (puNameProperty == null || !(puNameProperty.getValue() instanceof TypedStringValue)) {
            throw new RuntimeException(
                    "no property 'persistenceUnitName' defined on bean: " + emfContextBeanName);
        }
        String puName = ((TypedStringValue) puNameProperty.getValue()).getValue();

        // Get the name of the persistence unit for this EntityManagerFactory
        PropertyValue pumProperty = emfBeanDef.getPropertyValues().getPropertyValue("persistenceUnitManager");
        PersistenceUnitManager pum = null;
        if (pumProperty != null) {
            pum = createConfiguredPum(context, pumProperty);
        } else {
            pum = simulateDefaultPum(context, emfBeanDef);
        }

        // create the Hibernate configuration
        PersistenceUnitInfo pui = pum.obtainPersistenceUnitInfo(puName);
        Configuration configuration = new Configuration();
        configuration.setProperties(pui.getProperties());
        for (String className : pui.getManagedClassNames()) {
            configuration.addAnnotatedClass(Class.forName(className));
        }

        return configuration;
    } finally {
        context.close();
    }
}