Simple data access layer with Hibernate

xiaoxiao2021-03-06  84

Original version http://www.ociweb.com/jnb/jnbnov2003.html

1.1 Introduction

There are now many open source data access API tools, they can simplify data access. Prior to this, data access and query is performed through JDBC or via SQL string. These retrieval usually return the result set, the application matches the data type of the return column through the store program. In terms of efficiency, this approach is very fragile because it relies on the character string and the code matching code matching, changing the name of the data table causes the code to find all instances and modify them.

A better data storage method is to retrieve and update data using a simple and direct API without handwriting. The best implementation is not to rely on JDBC, SQL strings, and result sets, using a neutral way to solve. This scheme can establish a natural mapping between Java objects and database entities, which only require a small number of manual code to maintain mapping without deleting the data retrieval and control tools provided by JDBC.

1.2 hibernate

Hibernate is an open source object relationship mapping tool that reduces the direct operation of JDBC. Hibernate makes data retrieval and update, transaction, and database connection pools easier. Hibernate also matches database structure to generate Java source code.

The XML file contains Hibernate to configure data for the required database information. These files contain details of database connections, connection pool details, transaction factory settings, and other XML files to describe tables in the database. The combination of these XML files provides powerful configurability, which allows applications to adjust the behavior and performance of the data access layer, and improve the level of granularity.

1.3 code constructor

Hibernate comes with a code constructor component that generates a Java source file based on an object relationship map and outputs in the form of an XML configuration file. These files map database tables and field columns to Java class files, match the corresponding data type, identify the primary key field, and determine the physical relationship (one-to-one, one-to-man, man-to-one, etc.). Below is an ORDER XML configuration file example:

This XML file tells hibernate using a class called COM.OCIWeb.Order, which has three original fields: long type field ID, Boolean type field paymentConfirmed, Short type field installments. There are also three fields to represent relationships between the other three entities: Customer fields (involving Customer objects, Many-to-one relationships), orderItems fields (involving OrderItem objects, One-to-Many relationship), Delivery field (with Delibery object, representing one-to-one relationship). Hibernate All work is to use the details in the configuration file to maintain the relationship of all tables in the database. The above XML file also represents the relationship entity between "Lazy" load tables, involves two-way associations (using the Inverse property), which is deleted when the primary table is deleted (CASCADE attribute). Hibernate takes advantage of Outer Join Fetching (using a Many-to-One or One-to-One relationship to retrieve multiple objects as an object) reduces the number of interactions of the database. The above configurability features make Hibernate very powerful.

MiddleGen is also an open source tool that can connect to the database server, verifying database origin discovery table definitions and relationships. Middlegen comes with a Hibernate plugin to automatically generate the Hibernate configuration file. MiddleGen and Hibernate Code Build programs can run with Ant. 1.4 service layer

Constructing a level used to separate applications and Hibernate is a very good way, it is used to reduce coupling. The service layer is responsible for the interface implementation and management transaction boundary of Hibernate data retrieval. We can determine interface mode to manage access to Domain objects; it includes the desired Crud (Create, Read, Update, Delete) method, a method of accessing the Domain object through the primary key and a method of querying all Domain object instances. This mode is suitable for most Domain objects that are mapped to the application database. The interface of this mode is defined as follows:

This interface can be used to instantiate any DomainoJBect (that is, the interface exists in each Domain class). Define similar interfaces to manage all Domain objects. We also need a service locator to return an instance implemented by the interface. We define a Service Locator interface to define a simple method to receive the returned Domain object management interface class instance. The interface is defined as follows:

ServiceLocator can access through Singleton mode, for example:

The above code is very simple and an example of direct use of the service layer. The code implementation does not require the ServiceLocator and Domain objects (how to mention above the orderManager) implementation. This framework makes full use of interface implementation makes testing and parallel development easier. As long as the interface provided is constrained, the code of other people can fully imitate the interface.

Each method of the interface of the Domain Object Manager can be split into a separate command. So an AddCommand can be defined as a new Domain object record, which can also implement UpdateCommand and DeleteCommand. The Finder method can also be unified. Regardless of how to implement, create separate classes to implement each Domain manager interface, hide the Domain Manager interface and call the appropriate command. The figure below describes the planning of interfaces and implementation:

The following COMMAND interface includes an instance called the Domain Object Manager interface method, along with a call parameter that is passed, includes a Hibernate Session object. The Hibernate session interface provides a convenient persistence and query method required for Commands.

ServiceLocatorIMPL is responsible for returning an object instance given by the Domain Manager. All interfaces implements a dynamic proxy delegate method to call the appropriate command object (All of the interfaces will be used by a dynamic proxy That Will Delegate Method Invocations to a Correesponding Command Object. Dynamic agent's translation is not known). It has three responsibilities: provide a method to access any command object, acknowledgment class object incoming the getManager method, and create a proxy response method to call the commissioned response. Refer to the example.

ValidateSinterface () and validatehasdomainObjectmgrapi () just use to detect if the passed class is interface. It contains all Domain Object Manager Mode Method Description. Those characteristics of the methods are not checked, which is also possible to improve.

Another important aspect is the GetSession method for the ManageDelegate internal class, with a ThreadSessionHolder call to get an instance of the Hibernate Session object. By providing the name, ThreadSessionHolder is associated with a current Hibernate Session Executing thread. Hibernate session is used to retrieve and update mapped to the database table record object, which can cache a persistent object to keep an object instance that has been retrieved. By associating session and current Executing threads, object retrieval through different Daomain object managers will be able to build and eliminate the relationship between them without displaying sharing the same session. The result of this design is the range of session needs to be managed in some way. In J2EE applications, the Session range can occur in the request level, so each Domain Object Manager calls a normal session through a separate shared request, which is turned off when the response is returned. For a non-J2EE application, an approximate model can also be used as long as there is a component for the request. 1.5 FindwithnamedQuery

The ResolVecommand method in ManagerDelegate is trying to retrieve a matchup method command object. If not found, it will verify whether the name of the call method is started with FIND, so returns a command FindwithnamedQuery that does not implement. This command takes advantage of Hibernate naming query. This command has any positioning query support, which can be embodied in the Domain object interface. The only requirement of these queries is that their methods must begin with the java.util.collection instance, and the naming must match the XML configuration file. For example, a Finder method can be added to the DomainObjectmgr interface, which can be instantiated by name.

Public Collection FindMainObjectByName (String Name) throws lookupexception;

Hibernate profile requires a element, name, and HQL query details:

From com.ociweb.bean.domainObject As DomainObject

Where DomainObject.name =?]]>

The query definition in the mapping file must be named in a complete path, such as com.ociweb.domain.domainObjectmgr.FindDomainObjectByname.

1.6 transaction processing

From the above figure, you can see three Commands extends through TransactionalCommand as the base class. The purpose of this class is to include Execution in a transaction. This class calls its execute () to start transaction, call abstract methods (Command ()), this abstract method is implemented in its subclass. The TRANSACTIONALCOMMAND class is as follows:

Addcommand is very simple and very simple, and it also shows that it is very simple to use the Hibernate API.

1.7 flexible query

Like simple search and lasting data, Hibernate provides a very robust query API that supports query strings, named queries, and associated construct queries. The query API exposes two interfaces, Query interface and Criteria support HQL (Hibernate Query Language) syntax and associated queries. 1.7.1 query

The Hibernate session interface uses the factory method call, you can create a createQuery () method by incoming an HQL string or by calling the getNamedQuery () method, it can pass the query name that has been defined in the configuration file. Hibernate Query objects can use static values ​​(for example, from com.ociweb.custor) or parameterized query (for example, from com.ociweb.custor) Customer WHERE CUSTOMER .name =?) Execute operation. In fact, the parameterized query can be defined in two ways, one is to use the question mark instead of the parameter value, and the other is to use the named parameter to replace the question mark. For example: from com.ociweb.customer as customer where customer.name =: name. : Name parameter replaces the association value of the incoming (String Name, String Value). The advantage of using the named parameter is that the parameters can appear multiple times and the value can be the same.

1.7.2 criteria

The criteria interface is similar to the query, allowing to build a subquery association. Just like the Query interface, Hibernate Session is also operated through the factory. Association created via the Expression class, it has a way to create an informational expression (such as "Greater Than", "Less Than", "Like", "BetWeen", "Equals", "AND", "not").

1.8 review

The above described must have a first database definition, then utilize the tool to generate the Hibernate XML configuration file, which provides a mapping relationship between database entities and Java objects, as well as their corresponding Java object class source code. In addition, this lightweight data access layer can provide a simple and universal, and independent Hibernate application. It brings us a complete reusable persistent layer framework that makes full use of code generation features, so it is a vital application mode. This framework is very common and is easy to expand, so Hibernate does not require the data manager of the formation.

1.9 conclusion

There are now many tools and technologies to provide data problem solutions, such as data-driven applications, but also data management models. Two tools in these tools, Hibernate, and MiddleGen combine object representation of the entity model.

Zip File Containing All Source Code for the Sample Framework (3.7m size) zip file containing html representation of the sample framework source code (80k size)

转载请注明原文地址:https://www.9cbs.com/read-107416.html

New Post(0)