Class HibernateUtil


  • public class HibernateUtil
    extends Object
    This class collects most of the functionality we need for using Hibernate.
    Version:
    2.0
    Author:
    Nicklas, Samuel
    Last modified
    $Date: 2019-06-14 14:54:55 +0200 (fre, 14 juni 2019) $
    • Field Detail

      • log

        private static final org.slf4j.Logger log
        Log core events.
      • logSql

        private static final org.slf4j.Logger logSql
        Log all batcher SQL statements.
      • cfg

        private static MetadataSources cfg
        The Hibernate configuration, including all mappings.
      • metadata

        private static Metadata metadata
        The mappings related to a configuration.
      • dialect

        private static Dialect dialect
        The Hibernate database dialect in use.
      • dbEngine

        private static DbEngine dbEngine
        Our extra database specific sql generation that is not possible by the Hibernate dialect.
      • isInitialised

        private static boolean isInitialised
      • jdbcFetchSize

        private static int jdbcFetchSize
        Number of rows to load at a time when iterating over a result set.
        Since:
        3.9
    • Constructor Detail

      • HibernateUtil

        public HibernateUtil()
    • Method Detail

      • init1

        static void init1()
                   throws BaseException
        First step of initialising this class. This is done at startup time by the Application.start() method. In this step we load configuration settings from the 'base.config' and 'hibernate.cfg.xml' files and create the Dialect and DbEngine objects. Initialising means that we load the configuration from the properties and the xml file, read all mapping files, generate additional mappings for the ExtendableData items and raw data, and generate filters used by Query implementation.
        Throws:
        BaseException
      • init2

        static void init2()
                   throws BaseException
        Second step of initialising this class. This is done at startup time by the Application.start() method. In this step we read all mapping files, generate additional mappings for the ExtendableData items and raw data, and generate filters used by Query implementation.
        Throws:
        BaseException
      • unload

        static void unload()
        Unload all settings.
      • getConnectionProperties

        private static Properties getConnectionProperties()
                                                   throws BaseException
        Read database configuration properties from the base.config file and map them to Hibernate settings.
        Returns:
        Properties for database connection
        Throws:
        BaseException
        Since:
        3.8
      • checkJdbcDriver

        private static void checkJdbcDriver​(String dbUrl,
                                            String dbUser,
                                            String dbPassword)
        Check that a JDBC driver is registered and try to load a driver if not.
      • addStaticMappings

        private static void addStaticMappings​(MetadataSources cfg,
                                              HibernateUtil.FilterConfigurator filterConfig)
                                       throws BaseException
        Read all mapping files, which must be named Class.hbm.xml where class is the name of each class. The must be located in the same directory as the class files, and we support loading the xml files both from a jar file of from the directory.
        Throws:
        BaseException
      • manipulateDocument

        private static void manipulateDocument​(Document dom,
                                               HibernateUtil.FilterConfigurator filterConfig)
        Some XML files require manipulation by us before they are registered.
        • Add extended properties to extendable classes
        • Add filter implementation to almost all classes
        • Other special-case fixes depending on the underlying database
      • addExtendedProperties

        private static void addExtendedProperties​(Element classTag,
                                                  String className)
        Append <property> tags to the given class tag.
        Parameters:
        classTag - An Element representing a <class> tag
        className - The name of the (ExtendableData) class
        Since:
        2.17
      • createPropertyElement

        private static Element createPropertyElement​(ExtendedProperty property,
                                                     Namespace ns)
        Creates a <property> tag from an extended property definition. This also works for raw data properties since they extend from ExtendedProperty.
        Since:
        2.17
      • addFilterConditions

        private static void addFilterConditions​(Element classTag,
                                                String className,
                                                HibernateUtil.FilterConfigurator filterConfig)
        Add <filter> conditions to the given class tag.
        Parameters:
        classTag - An Element representing a <class> tag
        className - The name of the entity class
        Since:
        2.17
      • addSqlFunctions

        private static void addSqlFunctions​(SessionFactoryBuilder sfBuilder,
                                            DbEngine dbEngine)
        Add more SQL functions to HQL that are not present in a standard Hibernate installation. SQL functions are registered on the configuration with Configuration.addSqlFunction(String, SQLFunction). Note! The name of the function must be in lower-case letters, otherwise Hibernate will not be able to find it. In HQL, it is possible to use both lower-case and uppercase.

        Here are the functions registered so far.

        • rlike: Match a string against a regular expression
        Since:
        2.8, 3.8
      • fixUnitSymbolColumnDefinition

        private static void fixUnitSymbolColumnDefinition​(Element classTag)
        Fixes the definition of the UnitSymbols.symbol column so that it is case-sensitive. We need because some units have both milli (m) and Mega (M) as prefix (eg. mV and MV)
        Since:
        2.17
      • createStaticTables

        static int createStaticTables​(SchemaGenerator.Mode mode,
                                      ProgressReporter progress)
                               throws BaseException
        Create the all tables in the database. The database must exists and we recommend that it is empty to begin with.
        Returns:
        The schemaVersion that is currently installed
        Throws:
        BaseException
      • isEmptyDatabase

        static boolean isEmptyDatabase()
                                throws BaseException
        Check if the main database has any tables.
        Returns:
        TRUE if there are any tables, FALSE otherwise
        Throws:
        BaseException
      • dropVirtualTable

        static void dropVirtualTable​(VirtualDb db,
                                     VirtualTable table)
                              throws BaseException
        Drop a table in the dynamic database. The real table name is given by the VirtualTable.getTableName(VirtualDb). If the table doesn't exists this method does nothing. This method uses a separate connection to the database because some databases (ie. MySQL) can't handle transactions properly for this type of SQL statements.

        This method uses classes in the org.hibernate.mapping package to define a Hibernate representation of the table and uses the Table.sqlDropString method to generate the SQL. This should ensure that this code works with all database engines supported by Hibernate.

        Parameters:
        db - The virtual db item
        table - Information about the table to drop
        Throws:
        BaseException
        See Also:
        createVirtualTable(VirtualDb, VirtualTable), virtualTableExists(VirtualDb, VirtualTable)
      • dropDynamicTable

        static void dropDynamicTable​(String tableName)
      • newDynamicMapping

        private static Table newDynamicMapping​(VirtualDb db,
                                               VirtualTable table,
                                               boolean withColumns)
        Create a new org.hibernate.mapping.Table object for the specified table. This method is used by createVirtualTable(VirtualDb, VirtualTable) to build the mapping information Hibernate requires to generate the SQL to create the table.
        Parameters:
        db - The virtual db item
        table - Information about the table to generate the mapping for
      • addColumn

        private static void addColumn​(MetadataImplementor metadata,
                                      Table hibernateTable,
                                      VirtualColumn column)
        Add a column to a table. This method is used by newDynamicMapping(VirtualDb, VirtualTable, boolean) to build the mapping information Hibernate requires to generate the SQL to create the table.
        Parameters:
        hibernateTable - The org.hibernate.mapping.Table object that holds the mapping for the table
        column - The column to add to the table
      • newTransaction

        static Transaction newTransaction​(Session session)
                                   throws BaseException
        Create a new transaction for a session. If a transaction has already been created for the session, that one is returned.
        Throws:
        BaseException
      • getConnection

        static Connection getConnection​(Session session)
        Get the underlying JDBC connection from the Hibernate session. Hibernate 3.3 have implemented a partial replacement for the Session.connection() method that can be used if the connection or any derived object such as a PreparedStatement or ResultSet is not needed after the connection has been used. Such code should use doWork(Session, Work) instead.

        Other code may continue using this method until the Hibernate team develops a full replacement. See http://forum.hibernate.org/viewtopic.php?t=974518

        Since:
        2.4
        See Also:
        doWork(Session, Work)
      • getSessionFactory

        static SessionFactory getSessionFactory()
        Get the configured session factory.
        Since:
        2.15
      • doWork

        static void doWork​(Session session,
                           Work work)
                    throws SQLException
        Execute some arbitrary JDBC code using the same database connection as the Hibernate session. This method should be used instead of getConnection(Session) wherever possible.
        Parameters:
        session - The Hibernate session to use
        work - The work implementation
        Throws:
        SQLException - In case there is an SQL error
        Since:
        3.4
      • doReturningWork

        static <R> R doReturningWork​(Session session,
                                     ReturningWork<R> work)
                              throws SQLException
        Execute some arbitrary JDBC code using the same database connection as the Hibernate session. This method should be used instead of getConnection(Session) wherever possible.
        Parameters:
        session - The Hibernate session to use
        work - The work implementation
        Returns:
        Determined by the work implementation
        Throws:
        SQLException - In case there is an SQL error
        Since:
        3.4
      • close

        static void close​(Session session)
        Close a session.
      • close

        static void close​(StatelessSession session)
        Close a statless session.
      • loadData

        static <T> T loadData​(Session session,
                              Class<T> clazz,
                              int id)
                       throws BaseException
        Load a data item from the database when you know the id.
        Parameters:
        session - The Hibernate session which is connected to the database
        clazz - An object of this class is returned with the data
        id - The id of the item to load
        Throws:
        BaseException
      • loadData

        static <T> T loadData​(Session session,
                              Class<T> clazz,
                              String entityName,
                              int id)
                       throws BaseException
        Load a data item from the database when you know the id.
        Parameters:
        session - The Hibernate session which is connected to the database
        clazz - An object of this class is returned with the data
        entityName - The entity name of the item
        id - The id of the item to load
        Throws:
        BaseException
        Since:
        2.15
      • refresh

        static void refresh​(Session session,
                            BasicData data)
        Reload the data from the database for a given entity.
        Parameters:
        session - The Hibernate session which is connected to the database
        data - The entity to reload
        Since:
        2.4
      • unwrapIfProxy

        static BasicData unwrapIfProxy​(Session session,
                                       BasicData data)
        If the given data object is a proxy, load the real data object instead.
        Since:
        3.3.3
      • exists

        static boolean exists​(Session session,
                              Class<?> clazz,
                              int id)
        Checks if an item with the specified ID exists in the database.
        Parameters:
        session - The Hibernate session which is connected to the database
        clazz - The type of the item
        id - The ID of the item
        Returns:
        TRUE if the item exists in the database, FALSE otherwise
        Since:
        2.4
      • loadData

        static <T> T loadData​(StatelessSession session,
                              Class<T> clazz,
                              int id)
                       throws BaseException
        Load a data item from the database using a statless session when you know the id.
        Parameters:
        session - The Hibernate stateless session which is connected to the database
        clazz - An object of this class is returned with the data
        id - The id of the item to load
        Throws:
        BaseException
      • loadData

        static <T> T loadData​(StatelessSession session,
                              Class<T> clazz,
                              String entityName,
                              int id)
                       throws BaseException
        Load a data item from the database using a statless session when you know the id.
        Parameters:
        session - The Hibernate stateless session which is connected to the database
        clazz - An object of this class is returned with the data
        entityName - The entity name of the item
        id - The id of the item to load
        Throws:
        BaseException
      • loadData

        static <T> T loadData​(Query<T> query)
                       throws BaseException
        Load a data item from the database using a query. If the query returns more than one item, only the first is returned.
        Parameters:
        query - A Query object which should select one item of the specified class
        Throws:
        BaseException
      • executeUpdate

        static int executeUpdate​(Query<?> query)
                          throws BaseException
        Exceute an update or delete query.
        Parameters:
        query - A Query object which is executed using the Query.executeUpdate() method
        Returns:
        The number of affected items
        Throws:
        BaseException
      • deleteData

        static void deleteData​(Session session,
                               BasicData data)
                        throws BaseException
        Delete a data item from the database. If the ID doesn't exist in the database this metod does nothing.
        Throws:
        BaseException
      • loadList

        static <T> List<T> loadList​(Query<T> query,
                                    SessionControl sc)
                             throws BaseException
        Load a List of items from the database using a query.
        Parameters:
        query - The query to execute
        sc - A optional SessionControl that is automatically protected from timeouts during the time the query is running
        Throws:
        BaseException
      • loadIterator

        static <T> ScrollIterator<T> loadIterator​(Query<T> query,
                                                  SessionControl sc)
                                           throws BaseException
        Scroll through the result of a query using an iterator.
        Parameters:
        query - The query to execute
        sc - A optional SessionControl that is automatically protected from timeouts during the time the query is running
        Throws:
        BaseException
        Since:
        3.12
      • getPredefinedQuery

        static Query<?> getPredefinedQuery​(Session session,
                                           String name,
                                           String... replacements)
                                    throws BaseException
        Get a predefined HQL query.
        Parameters:
        replacements - In the SQL string we look for {1}, {2}, ... and replace this with the contents of the string array
        Throws:
        BaseException
        See Also:
        PredefinedQuery
      • getPredefinedQuery

        static <R> Query<R> getPredefinedQuery​(Session session,
                                               String name,
                                               Class<R> returnType,
                                               String... replacements)
                                        throws BaseException
        Get a predefined HQL query with a known return type.
        Parameters:
        replacements - In the SQL string we look for {1}, {2}, ... and replace this with the contents of the string array
        Throws:
        BaseException
        Since:
        3.12
        See Also:
        PredefinedQuery
      • getMapping

        static Mapping getMapping()
      • getDialect

        public static Dialect getDialect()
        Get the database dialect.
      • getDbEngine

        public static DbEngine getDbEngine()
        Get the database engine.
      • getJdbcFetchSize

        public static int getJdbcFetchSize()
        The number of rows to load at a time when reading from the database.
        Since:
        3.9
      • useThetaJoin

        public static boolean useThetaJoin​(QueryType queryType)
        Check if theta joins or ANSI joins are used by the database.
        Parameters:
        queryType - Query type to be checked.
        Returns:
        TRUE if theta joins are used, FALSE if ANSI joins are used.
      • quote

        public static String quote​(String value)
        Quote a string with the default quote type for the current database engine. Ie. with MySQL: value --> `value`, and with any ANSI-compatible database: value --> "value". This method uses the Dialect.openQuote and Dialect.closeQuote methods of the currently installed Hibernate dialect.
        Parameters:
        value - The value to quote
        Returns:
        The quoted value
        See Also:
        getDialect()
      • getShortEntityName

        static String getShortEntityName​(String entityName)
        Removes the package name part of a class name and any ending 'Data'.
      • dynamicDbIndexes

        public static void dynamicDbIndexes​(boolean verbose,
                                            boolean silent,
                                            boolean dropIndexes)
        Prints a lot of useful stuff about the dynamic database to standard output. For each table the output includes information about columns, indexes, primary keys and foreign keys as found in the current database.
        Parameters:
        verbose - If true, lots of information will be printed
        silent - If true, no information will be printed
        dropIndexes - If true, all indexes will be dropped
      • dbIndexes

        public static void dbIndexes​(boolean verbose,
                                     boolean silent,
                                     boolean dropIndexes,
                                     boolean updateIndexes)
        Prints a lot of useful stuff about the database to standard output. For each table the output includes information about columns, indexes, primary keys and foreign keys as found in the Hibernate mapping information and in the current database.
        Parameters:
        verbose - If true, lots of information will be printed
        silent - If true, no information will be printed
        dropIndexes - If true, all indexes will be dropped
        updateIndexes - If true, indexes that doesn't already exist will be created