com.netradius.hibernate.support.HibernateUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.netradius.hibernate.support.HibernateUtil.java

Source

/**
 * Copyright 2009-2013 NetRadius, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.netradius.hibernate.support;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hsqldb.jdbc.JDBCDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.*;

/**
 * Provides hibernate support and some additional database related utility
 * methods.
 *
 * @author Erik R. Jensen
 */
public final class HibernateUtil {

    private static final Logger log = LoggerFactory.getLogger(HibernateUtil.class);
    private static SessionFactory sessionFactory;

    private HibernateUtil() {
    }

    /**
     * Initializes hibernate and related resources.
     *
     * @param classes the annotated hibernate bean classes to load
     */
    public static void init(Class<?>... classes) {
        if (sessionFactory == null) {
            log.debug("Initializing hibernate.");
            Configuration config = new Configuration()
                    .setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
                    .setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver")
                    .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:testdb")
                    .setProperty("hibernate.connection.username", "sa")
                    .setProperty("hibernate.connection.password", "")
                    .setProperty("hibernate.connection.pool_size", "1")
                    .setProperty("hibernate.connection.autocommit", "false")
                    .setProperty("hibernate.cache.provider_class", "org.hibernate.cache.HashtableCacheProvider")
                    .setProperty("hibernate.hbm2ddl.auto", "create-drop").setProperty("hibernate.show_sql", "false")
                    .setProperty("hibernate.current_session_context_class", "thread");
            for (Class<?> clazz : classes) {
                log.debug("Loading class " + clazz.getName());
                config.addAnnotatedClass(clazz);
            }
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties())
                    .buildServiceRegistry();
            sessionFactory = config.buildSessionFactory(serviceRegistry);
            log.debug("Hibernate initialized.");
        }
    }

    /**
     * Closes the Hibernate session factory and related resources.
     */
    public static void close() {
        if (sessionFactory != null) {
            log.debug("Closing hibernate.");
            sessionFactory.close();
            sessionFactory = null;
            log.debug("Hibernate closed.");
        }
    }

    /**
     * Returns the current Hibernate session.
     *
     * @return the hibernate session
     */
    public static Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * Returns a JDBC connection from the Hibernate session factory.
     *
     * @return the JDBC connection
     * @throws SQLException if an error occurred obtaining a connection
     */
    public static Connection getConnection() throws SQLException {
        return JDBCDriver.getConnection("jdbc:hsqldb:mem:testdb", new Properties());
    }

    @SuppressWarnings("unchecked")
    public static <T> T query(String query, ResultSetHandler<T> handler, Object... params) throws SQLException {
        final Connection con = getConnection();
        try {
            return (T) new QueryRunner().query(con, query, handler, params);
        } finally {
            DbUtils.close(con);
        }
    }

    /**
     * Utilitiy method to close JDBC connections, statements and result sets.
     *
     * @param con the connection to close or null
     * @param stmt the statement to close or null
     * @param rs the result set to close or null
     */
    public static void close(Connection con, Statement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException x) {
                log.error("Error closing result set: " + x.getMessage(), x);
            }
        }
        if (stmt != null) {
            try {
                con.close();
            } catch (SQLException x) {
                log.error("Error closing statement: " + x.getMessage(), x);
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException x) {
                log.error("Error closing connection: " + x.getMessage(), x);
            }
        }
    }

    /**
     * Prints out all table details to stdout.
     */
    public static void printTables() {
        prettyPrint(getTables());
    }

    /**
     * Prints out the column details for a given table name to stdout.
     *
     * @param table the table name
     */
    public static void printColumns(String table) {
        prettyPrint(getColumns(table));
    }

    private static List<String[]> getTables() {
        final List<String[]> rows = new ArrayList<String[]>();
        rows.add(new String[] { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "TABLE_TYPE", "REMARKS", "TYPE_CAT",
                "TYPE_SCHEM", "TYPE_NAME", "SELF_REFERENCING_COL_NAME", "REF_GENERATION " });
        Connection con = null;
        ResultSet rs = null;
        try {
            con = getConnection();
            final DatabaseMetaData md = con.getMetaData();
            rs = md.getTables(null, null, "%", null);
            while (rs.next()) {
                List<String> s = new ArrayList<String>(10);
                for (int i = 10; i > 0; i--)
                    s.add(rs.getString(i));
                rows.add(s.toArray(new String[10]));
            }
        } catch (SQLException x) {
            log.error("Error listing tables: " + x.getMessage(), x);
        } finally {
            close(con, null, rs);
        }
        return rows;
    }

    private static List<String[]> getColumns(final String table) {
        final List<String[]> rows = new ArrayList<String[]>();
        rows.add(new String[] { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME",
                "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "NUM_PREC_RADIX", "NULLABLE", "REMARKS",
                "COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION",
                "IS_NULLABLE", "SCOPE_CATLOG", "SCOPE_SCHEMA", "SCOPE_TABLE", "SOURCE_DATA_TYPE",
                "IS_AUTOINCREMENT" });
        Connection con = null;
        ResultSet rs = null;
        try {
            con = getConnection();
            final DatabaseMetaData md = con.getMetaData();
            rs = md.getColumns(null, null, table, "%");
            while (rs.next()) {
                List<String> s = new ArrayList<String>(23);
                for (int i = 23; i > 0; i--)
                    s.add(rs.getString(i));
                rows.add(s.toArray(new String[23]));
            }
        } catch (SQLException x) {
            log.error("Error describing table: " + x.getMessage(), x);
        } finally {
            close(con, null, rs);
        }
        return rows;
    }

    /**
     * Pretty prints a list of String arrays. This method assumes the first array in the list
     * is the header.
     *
     * @param rows the rows to print
     */
    private static void prettyPrint(List<String[]> rows) {
        if (!rows.isEmpty()) {
            final int numCol = rows.get(0).length;
            final int[] maxLength = new int[numCol];
            Arrays.fill(maxLength, 0);
            for (String[] row : rows) {
                for (int i = row.length - 1; i >= 0; i--) {
                    if (row[i] == null && maxLength[i] < 4)
                        maxLength[i] = 4;
                    else if (row[i] != null && row[i].length() > maxLength[i])
                        maxLength[i] = row[i].length();
                }
            }
            final StringBuilder sb = new StringBuilder();
            int totalLength = 0;
            for (int i = 0; i < maxLength.length; i++) {
                totalLength += maxLength[i];
                if (i == 0)
                    sb.append("| ");
                sb.append("%").append(i + 1).append("$-").append(maxLength[i]).append("s | ");
                if (i == maxLength.length - 1)
                    sb.append("\n");
            }
            totalLength += numCol * 3 + 1;
            final String pattern = sb.toString();
            final Formatter formatter = new Formatter(System.out);
            System.out.print(line('=', totalLength));
            for (int i = 0; i < rows.size(); i++) {
                formatter.format(pattern, (Object[]) rows.get(i));
                if (i == 0)
                    System.out.print(line('=', totalLength));
                else
                    System.out.print(line('-', totalLength));
            }
        }
    }

    private static String line(char c, int num) {
        final StringBuilder sb = new StringBuilder();
        for (; num > 0; num--) {
            sb.append(c);
        }
        return sb.append("\n").toString();
    }

}