Example usage for org.hibernate Session doWork

List of usage examples for org.hibernate Session doWork

Introduction

In this page you can find the example usage for org.hibernate Session doWork.

Prototype

void doWork(Work work) throws HibernateException;

Source Link

Document

Controller for allowing users to perform JDBC related work using the Connection managed by this Session.

Usage

From source file:org.joda.time.contrib.hibernate.TestPersistentPeriod.java

License:Apache License

public void testSimpleStore() throws SQLException, IOException {
    Session session = getSessionFactory().openSession();

    for (int i = 0; i < periods.length; i++) {
        SomethingThatHappens thing = new SomethingThatHappens();
        thing.setId(i);/*w w w.  j  av  a  2 s .co m*/
        thing.setName("test_" + i);
        thing.setThePeriod(periods[i]);
        session.save(thing);
    }

    session.flush();
    session.doWork(new Work() {
        public void execute(Connection connection) throws SQLException {
            connection.commit();
        }
    });
    session.close();

    for (int i = 0; i < periods.length; i++) {
        session = getSessionFactory().openSession();
        SomethingThatHappens happeningThing = (SomethingThatHappens) session.get(SomethingThatHappens.class,
                new Long(i));

        Assert.assertNotNull(happeningThing);
        Assert.assertEquals(i, happeningThing.getId());
        Assert.assertEquals("test_" + i, happeningThing.getName());
        Assert.assertEquals(periods[i], happeningThing.getThePeriod());

        session.close();
    }

    // printSqlQueryResults("SELECT * FROM happening");
}

From source file:org.joda.time.contrib.hibernate.TestPersistentTimeOfDay.java

License:Apache License

public void testSimpleStore() throws SQLException {
    SessionFactory factory = getSessionFactory();

    Session session = factory.openSession();

    for (int i = 0; i < writeReadTimes.length; i++) {
        TimeOfDay writeReadTime = writeReadTimes[i];

        Schedule event = new Schedule();
        event.setId(i);//ww w  . j av a  2  s .  c o m
        event.setNextTime(writeReadTime);

        session.save(event);
    }

    session.flush();
    session.doWork(new Work() {
        public void execute(Connection connection) throws SQLException {
            connection.commit();
        }
    });
    session.close();

    for (int i = 0; i < writeReadTimes.length; i++) {
        TimeOfDay writeReadTime = writeReadTimes[i];

        session = factory.openSession();
        Schedule eventReread = (Schedule) session.get(Schedule.class, new Integer(i));

        assertNotNull("get failed - event#'" + i + "'not found", eventReread);
        assertNotNull("get failed - returned null", eventReread.getNextTime());

        TimeOfDay reReadTime = eventReread.getNextTime();
        if (writeReadTime.getHourOfDay() != reReadTime.getHourOfDay()
                || writeReadTime.getMinuteOfHour() != reReadTime.getMinuteOfHour()
                || writeReadTime.getSecondOfMinute() != reReadTime.getSecondOfMinute()) {
            fail("get failed - returned different date. expected " + writeReadTime + " was "
                    + eventReread.getNextTime());
        }

        if (writeReadTime.getMillisOfSecond() != reReadTime.getMillisOfSecond()) {
            System.out.println("millis different, might happen?");
        }
    }

    session.close();
}

From source file:org.joda.time.contrib.hibernate.TestPersistentTimeOfDayExact.java

License:Apache License

public void testSimpleStore() throws SQLException {
    SessionFactory factory = getSessionFactory();

    Session session = factory.openSession();

    for (int i = 0; i < writeReadTimes.length; i++) {
        TimeOfDay writeReadTime = writeReadTimes[i];

        Schedule event = new Schedule();
        event.setId(i);/*www .  j  a va  2s  .co m*/
        event.setNextTimeMillis(writeReadTime);

        session.save(event);
    }

    session.flush();
    session.doWork(new Work() {
        public void execute(Connection connection) throws SQLException {
            connection.commit();
        }
    });
    session.close();

    for (int i = 0; i < writeReadTimes.length; i++) {
        TimeOfDay writeReadTime = writeReadTimes[i];

        session = factory.openSession();
        Schedule eventReread = (Schedule) session.get(Schedule.class, new Integer(i));

        assertNotNull("get failed - event#'" + i + "'not found", eventReread);
        assertNotNull("get failed - returned null", eventReread.getNextTimeMillis());

        assertEquals("get failed - returned different date.", writeReadTime, eventReread.getNextTimeMillis());
    }

    session.close();
}

From source file:org.joda.time.contrib.hibernate.TestPersistentYearMonthDay.java

License:Apache License

public void testSimpleStore() throws SQLException {
    SessionFactory factory = getSessionFactory();

    Session session = factory.openSession();

    for (int i = 0; i < writeReadTimes.length; i++) {
        YearMonthDay writeReadTime = writeReadTimes[i];

        Schedule event = new Schedule();
        event.setId(i);/*  ww w  .  j ava  2  s  .  c  om*/
        event.setStartDate(writeReadTime);

        session.save(event);
    }

    session.flush();
    session.doWork(new Work() {
        public void execute(Connection connection) throws SQLException {
            connection.commit();
        }
    });
    session.close();

    for (int i = 0; i < writeReadTimes.length; i++) {
        YearMonthDay writeReadTime = writeReadTimes[i];

        session = factory.openSession();
        Schedule eventReread = (Schedule) session.get(Schedule.class, new Integer(i));

        assertNotNull("get failed - event#'" + i + "'not found", eventReread);
        assertNotNull("get failed - returned null", eventReread.getStartDate());

        assertEquals("get failed - returned different date", writeReadTime, eventReread.getStartDate());
    }

    session.close();
}

From source file:org.kalypso.model.wspm.pdb.internal.update.WorkRunnable.java

License:Open Source License

@Override
public IStatus execute(final IProgressMonitor monitor) throws InvocationTargetException {
    Session session = null;

    try {/*from w  ww .  j a  v  a 2 s.c o  m*/
        monitor.beginTask(m_work.toString(), IProgressMonitor.UNKNOWN);

        session = m_connection.openSession();

        session.doWork(m_work);

        session.close();

        return m_okStatus;
    } catch (final PdbConnectException e) {
        throw new InvocationTargetException(e);
    } finally {
        PdbUtils.closeSessionQuietly(session);
    }
}

From source file:org.molasdin.wbase.hibernate.transaction.BasicHibernateTransactionProvider.java

License:Apache License

@Override
public Transaction<HibernateEngine> newTransaction(final TransactionDescriptor descriptor) {
    Session session = sessionFactory.openSession();
    session.doWork(new Work() {
        @Override//from  w  w  w.  ja  v  a 2 s.c om
        public void execute(Connection connection) throws SQLException {
            connection.setTransactionIsolation(descriptor.isolation().jdbcCode());
        }
    });
    org.hibernate.Transaction transaction = session.beginTransaction();
    return new BasicHibernateTransaction(new BasicHibernateEngine(session), transaction);
}

From source file:org.mycore.datamodel.classifications2.impl.MCRCategoryDAOImplTest.java

License:Open Source License

private void printCategoryTable() {
    Session session = MCRHIBConnection.instance().getSession();
    session.doWork(connection -> {
        try {//from   w w  w. j  av  a 2 s.com
            Statement statement = connection.createStatement();
            try {
                String tableName = getDefaultSchema().map(s -> s + ".").orElse("") + "MCRCategory";
                ResultSet resultSet = statement.executeQuery("SELECT * FROM " + tableName);
                printResultSet(resultSet, System.out);
            } catch (SQLException e1) {
                LogManager.getLogger().warn("Error while querying MCRCategory", e1);
            } finally {
                statement.close();
            }
        } catch (SQLException e2) {
            LogManager.getLogger().warn("Error while querying MCRCategory", e2);
        }
    });
}

From source file:org.n52.sos.ds.hibernate.H2Configuration.java

License:Open Source License

public static void recreate() {
    synchronized (LOCK) {
        if (instance == null) {
            throw new IllegalStateException("Database is not initialized");
        }//  w  ww  . ja  v  a2s  . c  o  m
        Session session = null;
        Transaction transaction = null;
        try {
            session = getSession();
            transaction = session.beginTransaction();
            session.doWork(new Work() {
                @Override
                public void execute(final Connection connection) throws SQLException {
                    Statement stmt = null;
                    try {
                        stmt = connection.createStatement();
                        for (final String cmd : instance.getDropScript()) {
                            stmt.addBatch(cmd);
                        }
                        for (final String cmd : instance.getCreateScript()) {
                            stmt.addBatch(cmd);
                        }
                        stmt.executeBatch();
                    } finally {
                        if (stmt != null) {
                            stmt.close();
                        }
                    }
                }
            });
            transaction.commit();
        } catch (final HibernateException e) {
            if (transaction != null) {
                transaction.rollback();
            }
            throw e;
        } finally {
            returnSession(session);
        }
    }
}

From source file:org.n52.sos.ds.hibernate.H2Configuration.java

License:Open Source License

public static void truncate() {
    synchronized (LOCK) {
        if (instance == null) {
            throw new IllegalStateException("Database is not initialized");
        }/*from  w  w  w  .j a v  a  2 s. c om*/
        final Iterator<Table> tableMappings = instance.getConfiguration().getTableMappings();
        final List<String> tableNames = new LinkedList<String>();
        GeoDBDialect dialect = new GeoDBDialect();
        while (tableMappings.hasNext()) {
            tableNames.add(tableMappings.next().getQuotedName(dialect));
        }
        Session session = null;
        Transaction transaction = null;
        try {
            session = getSession();
            transaction = session.beginTransaction();
            session.doWork(new Work() {
                @Override
                public void execute(final Connection connection) throws SQLException {
                    Statement stmt = null;
                    try {
                        stmt = connection.createStatement();
                        stmt.addBatch("SET REFERENTIAL_INTEGRITY FALSE");
                        for (final String table : tableNames) {
                            stmt.addBatch("DELETE FROM " + table);
                        }
                        stmt.addBatch("SET REFERENTIAL_INTEGRITY TRUE");
                        stmt.executeBatch();
                    } finally {
                        if (stmt != null) {
                            stmt.close();
                        }
                    }
                }
            });
            transaction.commit();
        } catch (final HibernateException e) {
            if (transaction != null) {
                transaction.rollback();
            }
            throw e;
        } finally {
            returnSession(session);
        }
    }
}

From source file:org.n52.sos.ds.hibernate.UnspecifiedSessionFactoryProvider.java

License:Open Source License

@Override
public void initialize(Properties properties) throws ConfigurationException {
    final DatasourceCallback datasourceCallback = getDatasourceCallback(properties);
    datasourceCallback.onInit(properties);
    try {//  ww  w  .ja  va2 s  .  co m
        LOGGER.debug("Instantiating configuration and session factory");
        configuration = getConfiguration(properties);
        configuration.mergeProperties(properties);

        // set timestamp mapping to a special type to ensure time is always
        // queried in UTC
        configuration.registerTypeOverride(new UtcTimestampType());
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        this.sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Session s = this.sessionFactory.openSession();
        try {
            HibernateMetadataCache.init(s);
            s.doWork(new Work() {
                @Override
                public void execute(Connection connection) throws SQLException {
                    datasourceCallback.onFirstConnection(connection);
                }
            });
        } finally {
            returnConnection(s);
        }
    } catch (HibernateException he) {
        String exceptionText = "An error occurs during instantiation of the database connection pool!";
        LOGGER.error(exceptionText, he);
        cleanup();
        throw new ConfigurationException(exceptionText, he);
    }
}