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:org.trianacode.TrianaCloud.Utils.DAO.java

License:Open Source License

private static SessionFactory buildSessionFactory() {
    try {//from  www  .  jav a  2 s.  c o  m
        // Create the SessionFactory from hibernate.cfg.xml
        Configuration configuration = new Configuration();
        configuration.configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                .buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        ex.printStackTrace();
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:org.ucieffe.index.QueryTester.java

License:Open Source License

public static void main(String[] args) {
    Configuration cfg = new Configuration();
    cfg.configure();
    SessionFactory sessionFactory = cfg.buildSessionFactory();
    QueryTester qt = new QueryTester(sessionFactory);
    qt.runTests();/*from   w  w w.  ja va2s.  c om*/
}

From source file:org.xchain.framework.hibernate.HibernateLifecycle.java

License:Apache License

/**
 * Does Hibernate configuration.// ww  w.j  ava 2 s. c  o  m
 * 
 * @param context
 */
@StartStep(localName = "hibernate-configuration", before = "hibernate")
public static void startHibernateConfig(LifecycleContext context) {
    if (installDefaultConfiguration()) {
        if (log.isInfoEnabled()) {
            log.info(
                    "Reading default Hibernate configuration from '/hibernate.cfg.xml' and '/hibernate.properties'.");
        }

        // Uses the hibernate annotation configuration, replace with Configuration() if you
        // don't use annotations or JDK 5.0
        Configuration configuration = new AnnotationConfiguration();

        ((AnnotationConfiguration) configuration).setNamingStrategy(new DefaultComponentSafeNamingStrategy());

        // Read not only hibernate.properties, but also hibernate.cfg.xml
        configuration.configure();

        // set the configuration.
        HibernateLifecycle.setConfiguration(configuration);

        // we will need to clean this up after the lifecycle has started.
        cleanUp = true;
    }
}

From source file:owldb.util.HibernateUtil.java

License:Open Source License

/**
 * Constructor.//from   w ww  .j  a  v a  2  s.  co  m
 * 
 * @param ontologyManager The owl ontology manager
 * @param hibernateProperties Additional Hibernate settings
 */
public HibernateUtil(final OWLOntologyManager ontologyManager, final Properties hibernateProperties) {
    try {
        final Configuration configuration = new Configuration();
        configuration.configure();
        final Interceptor interceptor = new OWLDBInterceptor(ontologyManager);
        configuration.setInterceptor(interceptor);

        final EventListeners listeners = configuration.getEventListeners();
        final OWLDBEventListener dbListener = new OWLDBEventListener();
        listeners.setSaveOrUpdateEventListeners(
                new SaveOrUpdateEventListener[] { dbListener, new DefaultSaveOrUpdateEventListener() });
        listeners.setSaveEventListeners(
                new SaveOrUpdateEventListener[] { dbListener, new DefaultSaveEventListener() });
        listeners.setPostCommitDeleteEventListeners(new PostDeleteEventListener[] { dbListener });
        listeners.setPostCommitInsertEventListeners(new PostInsertEventListener[] { dbListener });

        // Enable second level cache if not set otherwise
        if (hibernateProperties.get(Environment.USE_SECOND_LEVEL_CACHE) == null)
            hibernateProperties.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true");
        // Enable query cache if not set otherwise and second level is enabled
        if ("true".equals(hibernateProperties.get(Environment.USE_SECOND_LEVEL_CACHE))
                && hibernateProperties.get(Environment.USE_QUERY_CACHE) == null)
            hibernateProperties.setProperty(Environment.USE_QUERY_CACHE, "true");

        // Add additional specific Hibernate properties
        configuration.addProperties(hibernateProperties);

        // Create the SessionFactory from the configuration.
        this.factory = configuration.buildSessionFactory();
    } catch (final Throwable ex) {
        LOGGER.error("Initial SessionFactory creation failed.", ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:pkg.CriteriaProductCode.java

public static SessionFactory createSessionFactory() {
    Configuration configuration = new Configuration();
    configuration.configure();
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}

From source file:pl.edu.wat.cinema.util.HibernateUtil.java

private static SessionFactory configureSessionFactory() throws HibernateException {
    Configuration configuration = new Configuration();
    configuration.configure();
    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}

From source file:pl.pjaneczek.controller.ArchivesMessagesServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//w  ww  .j  a  v  a 2s  .c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");

    Configuration configuration = new Configuration();
    SessionFactory sessionFactory = configuration.configure().buildSessionFactory();
    Session ses = sessionFactory.openSession();
    Transaction transaction = ses.beginTransaction();
    Query query = ses.createQuery("from Message");
    List<Message> messagesList = query.list();

    //        JsonArray messagesArray = new JsonArray();
    //
    //        for (int i = 0; i < messagesList.size(); i++) {
    //            JsonObject messageObj = new JsonObject();
    //
    //            messageObj.addProperty("userId" + i, messagesList.get(i).getUserId());
    //            messageObj.addProperty("message" + i, messagesList.get(i).getContent());
    //
    //            messagesArray.add(messageObj);
    //
    //        }

    //        Gson gson = new GsonBuilder().setPrettyPrinting()
    //                .create();
    //        String json = gson.toJson(messagesArray);
    //        response.getWriter().write(json);
    String json = new Gson().toJson(messagesList);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

From source file:pl.pjaneczek.controller.CurrentLoginUsersServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Configuration configuration = new Configuration();
    SessionFactory sessionFactory = configuration.configure().buildSessionFactory();
    Session ses = sessionFactory.openSession();
    Transaction transaction = ses.beginTransaction();
    Query query = ses.createQuery("from User as user where user.isLogin = 1");
    List<User> userList = query.list();

    //        JsonArray userArray = new JsonArray();
    //        // w w w. j  ava  2  s .  c o m
    // 
    //        for (int i = 0; i < userList.size(); i++) {
    //            JsonObject userObj = new JsonObject();
    //            
    //            userObj.addProperty("firstName" + i, userList.get(i).getFirstName());
    //            userObj.addProperty("lastName" + i, userList.get(i).getLastName());
    //            
    //            userArray.add(userObj);
    //
    //        }

    //        Gson gson = new GsonBuilder().setPrettyPrinting()
    //                .create();
    //        String json = gson.toJson(userArray);
    //        response.getWriter().write(json);

    String json = new Gson().toJson(userList);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

From source file:postgreHibernateClient.postgreCacheClient.java

License:Open Source License

public boolean init() throws DBException {
    System.out.println("initializing.....");
    if (initialized)
        return true;
    try {//from  w w w  .ja  v  a2  s  .c o  m
        Configuration configuration = new Configuration();
        configuration.configure().setProperty("hibernate.show_sql", "false");
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                .buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        load_index = 0;
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object.: " + ex);
        throw new ExceptionInInitializerError(ex);
    }

    initialized = true;
    return true;
}

From source file:postgreHibernateClient.postgreHibClient.java

License:Open Source License

public boolean init() throws DBException {
    System.out.println("initializing.....");
    if (initialized)
        return true;
    try {/*from   w ww  .  j a va  2s.  c o  m*/
        Configuration configuration = new Configuration();
        configuration.configure().setProperty("hibernate.show_sql", "false");
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
                .buildServiceRegistry();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        session = sessionFactory.openSession();
        load_index = 0;
    } catch (Throwable ex) {
        System.err.println("Failed to create sessionFactory object.: " + ex);
        throw new ExceptionInInitializerError(ex);
    }

    initialized = true;
    return true;
}