Class HibernateUtil

java.lang.Object
net.sf.basedb.core.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: 2023-03-31 11:32:24 +0200 (Fri, 31 Mar 2023) $
  • Field Details

    • log

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

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

      private static SessionFactory sf
      The single SessionFactory.
    • 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 Details

    • HibernateUtil

      public HibernateUtil()
  • Method Details

    • 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
    • defineFilter

      private static void defineFilter​(Element classTag, Item itemType, String name, String condition, HibernateUtil.FilterConfigurator filterConfig)
      Define a filter for on the given class.
      Since:
      3.6
    • addRawDataMappings

      private static void addRawDataMappings​(MetadataSources cfg) throws BaseException
      Generate additional mappings for the raw data types.
      Throws:
      BaseException
    • 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
    • createVirtualTable

      static String createVirtualTable​(VirtualDb db, VirtualTable table) throws BaseException
      Create a table in the dynamic database. The real table name is given by the VirtualTable.getTableName(VirtualDb). It is assumed that the table doesn't already exists. This can be checked by virtualTableExists(VirtualDb, VirtualTable). 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.sqlCreateString 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 create
      Returns:
      The name of the created table
      Throws:
      BaseException
      See Also:
      dropVirtualTable(VirtualDb, VirtualTable), virtualTableExists(VirtualDb, VirtualTable)
    • 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)
    • virtualTableExists

      static boolean virtualTableExists​(VirtualDb db, VirtualTable table)
      Check if a table exists in the dynamic database or not. The real table name is given by the VirtualTable.getTableName(VirtualDb).

      This method uses JDBC DatabaseMetaData object on a separate connection to find out if the table exists or not.

      Parameters:
      db - The virtual db item
      table - Information about the table
      See Also:
      createVirtualTable(VirtualDb, VirtualTable), dropVirtualTable(VirtualDb, VirtualTable)
    • tableExists

      private static boolean tableExists​(String tableName, Session session) throws SQLException
      Check if table in the dynamic database exists.
      Parameters:
      tableName - The name of the table
      session - The Hibernate session
      Throws:
      SQLException
      See Also:
      virtualTableExists(VirtualDb, VirtualTable)
    • 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
    • getPlainConnection

      static Connection getPlainConnection() throws SQLException
      Throws:
      SQLException
    • newSession

      static Session newSession() throws BaseException
      Create a new Hibernate session.
      Throws:
      BaseException
    • newSession

      static Session newSession​(Connection c)
    • newSession

      static Session newSession​(Interceptor interceptor, Connection c) throws BaseException
      Create a new Hibernate session, optionally with an interceptor.
      Throws:
      BaseException
      Since:
      2.13
    • newStatelessSession

      static StatelessSession newStatelessSession​(Session session) throws BaseException
      Throws:
      BaseException
    • 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
    • commit

      static void commit​(Transaction tx) throws BaseException
      Commit a transaction.
      Throws:
      BaseException
    • rollback

      static void rollback​(Transaction tx) throws BaseException
      Rollback a transaction.
      Throws:
      BaseException
    • close

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

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

      static void flush​(Session session) throws BaseException
      Flush all changed objects to the database.
      Throws:
      BaseException
      See Also:
      clear(Session)
    • clear

      static void clear​(Session session) throws BaseException
      Clear the session of cached objects. Changes that has not been written to the database are lost.
      Throws:
      BaseException
      See Also:
      flush(Session)
    • saveData

      static void saveData​(Session session, BasicData data) throws BaseException
      Save a new data object to the database.
      Throws:
      BaseException
    • saveData

      static void saveData​(StatelessSession session, BasicData data) throws BaseException
      Save a new data object to the database.
      Throws:
      BaseException
    • updateData

      static void updateData​(Session session, BasicData data) throws BaseException
      Update an existing data object in the database.
      Throws:
      BaseException
    • lockData

      static void lockData​(Session session, BasicData data, LockOptions lockOptions) throws BaseException
      Reconnect a disconnected data object to the session, discarding changes that have been made while the object was disconnected. This method is most useful with lockOptions = LockOptions.NONE if the logged in user only has read permission to the object.
      Throws:
      BaseException
      See Also:
      DbControl.reattachItem(BasicItem, boolean)
    • 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
    • initCollection

      static void initCollection​(Session session, BasicData data, String collectionName) throws BaseException
      Initialise a collection on a data object. This method is useful if you plan to detach an item.
      Throws:
      BaseException
      See Also:
      DbControl.detachItem(BasicItem)
    • 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
    • evictData

      static void evictData​(Session session, BasicData data) throws BaseException
      Remove a data item from the internal cache of Hibernate. This also means that changes to the object will not be saved to the database unless it is reconnected again.
      Throws:
      BaseException
      See Also:
      updateData(Session, BasicData), lockData(Session, BasicData, LockOptions)
    • createQuery

      static <T> Query<T> createQuery​(Session session, String hql) throws BaseException
      Create a Hibernate query.
      Throws:
      BaseException
    • createQuery

      static <R> Query<R> createQuery​(Session session, String hql, Class<R> returnType) throws BaseException
      Create a Hibernate query with a known return type.
      Throws:
      BaseException
      Since:
      3.12
    • createQuery

      static <R> Query<R> createQuery​(StatelessSession session, String hql, Class<R> returnType) throws BaseException
      Create a Hibernate query using a stateless session and a known return type.
      Throws:
      BaseException
      Since:
      3.12
    • createSqlQuery

      static NativeQuery<?> createSqlQuery​(Session session, String sql) throws BaseException
      Create a Hibernate SQL query.
      Throws:
      BaseException
    • createSqlQuery

      static <R> NativeQuery<R> createSqlQuery​(Session session, String sql, Class<R> returnType) throws BaseException
      Create a Hibernate SQL query with a known return type.
      Throws:
      BaseException
      Since:
      3.12
    • createSqlQuery

      static NativeQuery<?> createSqlQuery​(StatelessSession session, String sql) throws BaseException
      Create a Hibernate SQL query using a stateless session.
      Throws:
      BaseException
    • createSqlQuery

      static <R> NativeQuery<R> createSqlQuery​(StatelessSession session, String sql, Class<R> returnType) throws BaseException
      Create a Hibernate SQL query with a known return type using a stateless session.
      Throws:
      BaseException
      Since:
      3.12
    • enableFilter

      static Filter enableFilter​(Session session, String name) throws BaseException
      Enable the filter with the given name.
      Throws:
      BaseException
    • disableFilter

      static void disableFilter​(Session session, String name) throws BaseException
      Disable the filter with the given name.
      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, boolean returnArray, 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) throws BaseException
      Get a predefined HQL query.
      Throws:
      BaseException
      See Also:
      PredefinedQuery
    • 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
    • getPredefinedQuery

      static <R> Query<R> getPredefinedQuery​(StatelessSession session, String name, Class<R> returnType) throws BaseException
      Get a predefined HQL query with a known return type using the stateless session.
      Throws:
      BaseException
      Since:
      3.12
      See Also:
      PredefinedQuery
    • getPredefinedSQLQuery

      static Query<?> getPredefinedSQLQuery​(Session session, String name, String... replacements) throws BaseException
      Get a predefined SQL query.
      Throws:
      BaseException
      See Also:
      PredefinedQuery
    • getPredefinedSQLQuery

      static <R> NativeQuery<R> getPredefinedSQLQuery​(Session session, String name, Class<R> returnType, String... replacements) throws BaseException
      Get a predefined SQL query with a known return type.
      Throws:
      BaseException
      Since:
      3.12
      See Also:
      PredefinedQuery
    • getPredefinedSQLQuery

      static NativeQuery<?> getPredefinedSQLQuery​(StatelessSession session, String name) throws BaseException
      Get a predefined SQL query using the stateless session.
      Throws:
      BaseException
      See Also:
      PredefinedQuery
    • getPredefinedSQLQuery

      static <R> NativeQuery<R> getPredefinedSQLQuery​(StatelessSession session, String name, Class<R> returnType) throws BaseException
      Get a predefined SQL query with a known return type using the stateless session.
      Throws:
      BaseException
      See Also:
      PredefinedQuery
    • getClassMappings

      static Iterator<PersistentClass> getClassMappings()
    • getClassMapping

      static PersistentClass getClassMapping​(String entityName)
    • getClassMetadata

      static ClassMetadata getClassMetadata​(String entityName)
    • 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'.
    • testTransactions

      static void testTransactions() throws BaseException
      Throws:
      BaseException
    • 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