Lazy initialization, a Hibernate problem. Java Persistence versus Hibernate .. .. Hibernate API. The basic idea of object relation mapping - ORM is to map database tables to a class. In order to get complete our application, we must undertake the following steps. Implementing POJO associations. Adding logic to accessor methods. Defining the mapping metadata. Metadata in XML. Basic property . Query information spread across several tables 9 □. Searching .. We will walk you through the steps of marking an entity and a property as indexed. Hibernate Search x is compatible with Hibernate Core x starting from. 2.
|Language:||English, Spanish, Portuguese|
|ePub File Size:||29.59 MB|
|PDF File Size:||11.55 MB|
|Distribution:||Free* [*Regsitration Required]|
Transactions. Preface ibernate ORM (Hibernate in short) is an object- relational mapping framework, facilitating the conversion of an object-oriented As a first step we will create a simple maven project on the command line. Hibernate Read Chapter 1, Introduction to Hibernate for a tutorial with step-by-step . In the next step, we tell Hibernate about this persistent class. Tutorial 4 – Hibernate, HSQL Database, Maven and Eclipse. This tutorial assumes To keep things simple, I will be using HypersonicSQL (aka HSQL) database, which is easy to use. This is an . ga. . Next step is to create the Hibernate configuration file “hibernate. soundofheaven.info” under.
The basic procedure for adding a child Category to a parent Category looks like this: Basically, we have the choice of adding either several columns or a single column of a new SQL data type. A number of commercial and open source Java ORM tools have achieved this level of quality. Almost all applications require persistent data. How transparent is the persistence tool?
My parent table will always have one record,but my child table can have multiple records. If possible,can you pls. Hi sir,I have done insert update delete using your jsf integration with spring and hibernate project but how can i search the values from database? If am giving customerid then showing about that name and address in text box and textarea. Bit late here, but all hibernate tutorials contain deprecated APIs.
Hi sir, I want to create a simple human resource application using hibernate framework. Are there any sample projects available on those?
Any help would be highly appreciated. Thank you: HI, Please help me for below situation. I have tables like: Please help me to prepare HQL. Whenever I google Spring or Java and Hibernate. Thanks a million.
Your tutorial is very helpful for me. Hello, I have a scenario, where i have to fetch parent table with specific childs not all. I want to fetch table A data with table B only not C. Do we have any configuration for the same. Other approach we thought was to remove mapping and fetch A and B using left join.
Hi We have a web app using hibernate 3 and a sql server database. Hi mkyoung can u please provide tag example , it is required. Hi , BuildSessionFactory also deprecated , so i think its better explain about it also.. Thank you.
Hibernate Tutorial By mkyong March 31, Updated: For online info For online information and ordering of this and other Manning books, please visit www. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact: All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.
Manning Publications Co. Tiffany Taylor Typesetter: Dottie Marsico Cover designer: SQL fundamentals appendix B: ORM implementation strategies B. Back in the real world C. While modern programming languages, including JavaTM, provide an intuitive, object-oriented view of application-level business entities, the enterprise data underlying these entities is heavily relational in nature.
Further, the main strength of the relational model—over earlier navigational models as well as over later OODB models—is that by design it is intrinsically agnostic to the programmatic manipulation and application-level view of the data that it serves up.
Many attempts have been made to bridge relational and object-oriented technologies, or to replace one with the other, but the gap between the two is one of the hard facts of enterprise computing today. Hibernate meets this challenge in a very pragmatic, direct, and realistic way. As Christian Bauer and Gavin King demonstrate in this book, the effective use of ORM technology in all but the simplest of enterprise environments requires understanding and configuring how the mediation between relational data and objects is performed.
This demands that the developer be aware and knowledgeable both of the application and its data requirements, and of the SQL query language, relational storage structures, and the potential for optimization that relational technology offers.
Not only does Hibernate provide a full-function solution that meets these requirements head on, it is also a flexible and configurable architecture. This book provides a comprehensive overview of Hibernate. It covers how to use its type mapping capabilities and facilities for modeling associations and inheritance; how to retrieve objects efficiently using the Hibernate query language; how to configure Hibernate for use in both managed and unmanaged environments; and how to use its tools.
In addition, throughout the book the authors provide insight into the underlying issues of ORM and into the design choices behind Hibernate. These insights give the reader a deep understanding of the effective use of ORM as an enterprise technology.
This kind of application creates, manages, and stores structured information and shares this information between many users in multiple physical locations. In the past five years, broad adoption of the Java programming language has brought about the ascendancy of the object-oriented paradigm for software development. Developers are now sold on the benefits of object orientation. However, the vast majority of businesses are also tied to long-term investments in expensive relational database systems.
Not only are particular vendor products entrenched, but existing legacy data must be made available to and via the shiny new objectoriented web applications. However, the tabular representation of data in a relational system is fundamentally different than the networks of objects used in object-oriented Java applications.
Traditionally, the importance and cost of this mismatch have been underestimated, and tools for solving the mismatch have been insufficient. Meanwhile, Java developers blame relational technology for the mismatch; data professionals blame object technology. For developers weary of tedious data access code, the good news is that ORM has come of age. Applications built with ORM middleware can be expected to be cheaper, more performant, less vendor-specific, and more able to cope with changes to the internal object or underlying SQL schema.
The astonishing thing is that these benefits are now available to Java developers for free. Hibernate began life as an independent, noncommercial open source project. The Hibernate team including the authors has learned ORM the hard way— that is, by listening to user requests and implementing what was needed to satisfy those requests. The result, Hibernate, is a practical solution, emphasizing developer productivity and technical leadership.
Hibernate has been used by tens of thousands of users and in many thousands of production applications. Hibernate joined jboss. It was also the source of many heated disputes and learning experiences. We hope you find it helpful and enjoy working with Hibernate.
A book is only as good as its reviewers, and we had the best.
Thanks for your endless hours of reading our half-finished and raw manuscript. Our team at Manning was invaluable.
Clay Andres got this project started, Jackie Carter stayed with us in good and bad times and taught us how to write. Marjan Bace provided the necessary confidence that kept us going. Tiffany Taylor and Liz Welch found all the many mistakes we made in grammar and style. Mary Piergies organized the production of this book.
Many thanks for your hard work. You made it possible. This persistence layer implementation covers all entity association, class inheritance, and special type mapping strategies.
We teach you how to tune the Hibernate object query and transaction system for the best performance in highly concurrent multiuser applications. The flexible Hibernate dual-layer caching system is also an important topic in this book. We discuss Hibernate integration in different scenarios and also show you typical architectural problems in two- and three-tiered Java database applications.
Roadmap Chapter 1 defines object persistence. Chapter 2 gives an architectural overview of Hibernate and shows you the most important application-programming interfaces. Chapter 3 introduces the example application and all kinds of entity and relationship mappings to a database schema, including uni- and bidirectional associations, class inheritance, and composition. Chapter 4 teaches you the Hibernate interfaces for read and save operations; we also show you how transitive persistence persistence by reachability works in Hibernate.
This chapter is focused on loading and storing objects in the most efficient way. Chapter 5 discusses concurrent data access, with database and long-running application transactions. We introduce the concepts of locking and versioning of data. We also cover caching in general and the Hibernate caching system, which are closely related to concurrent data access.
Chapter 6 completes your understanding of Hibernate mapping techniques with more advanced mapping concepts, such as custom user types, collections of values, and mappings for one-to-one and many-to-many associations. We show you how to translate complex search dialogs in your application to a query by example QBE query. Chapter 8 describes some basic practices of Hibernate application architecture. We show you how to design long-running application transactions and how to use the innovative detached object support in Hibernate.
We also talk about audit logging and legacy database schemas. Chapter 9 introduces several different development scenarios and tools that may be used in each case. We show you the common technical pitfalls with each approach and discuss the Hibernate toolset hbm2ddl, hbm2java and the integration with popular open source tools such as XDoclet and Middlegen.
Readers of this book should have basic knowledge of object-oriented software development and should have used this knowledge in practice. To understand the application examples, you should be familiar with the Java programming language and the Unified Modeling Language.
Our primary target audience consists of Java developers who work with SQLbased database systems. Since data access is the bottleneck in most Java applications, this book pays close attention to performance issues. Many DBAs are understandably nervous about entrusting performance to tool-generated SQL code; we seek to allay those fears and also to highlight cases where applications should not use tool-managed data access.
Code conventions and downloads This book provides copious examples, which include all the Hibernate application artifacts: Java code, Hibernate configuration files, and XML mapping metadata files. Source code in listings or in text is in a fixed-width font like this to separate it from ordinary text. Additionally, Java method names, component parameters, object properties, and XML elements and attributes in text are also presented using fixed-width font.
In rare cases, even this was not enough, and listings include line-continuation markers. Additionally, comments in the source code have been removed from the listings. In some cases, numbered bullets link to explanations that follow the listing.
Directions for downloading Hibernate, in source or binary form, are available from the Hibernate web site: The source code for all CaveatEmptor examples in this book is available from http: The CaveatEmptor example application code is available on this web site in different flavors: However, only the standalone persistence layer source package is the recommended companion to this book. About the authors Christian Bauer is a member of the Hibernate developer team and is also responsible for the Hibernate web site and documentation.
Christian is interested in relational database systems and sound data management in Java applications. He works as a developer and consultant for JBoss Inc. Gavin King is the founder of the Hibernate project and lead developer. He is an enthusiastic proponent of agile development and open source software. He is a developer and consultant for JBoss Inc.
Therefore, some of the information in any technical book becomes quickly outdated, especially when new standards and product versions are already on the horizon.
Hibernate3, an evolutionary new version of Hibernate, was in the early stages of planning and design while this book was being written. By the time the book hits the shelves, there may be an alpha release available. However, the information in this book is valid for Hibernate3; in fact, we consider it to be an essential reference even for the new version.
We discuss fundamental concepts that will be found in Hibernate3 and in most ORM solutions. Furthermore, Hibernate3 will be mostly backward compatible with Hibernate 2. For more up-to-date information, see the Hibernate road map: To access the forum and subscribe to it, point your web browser to www.
This page provides information on how to get on the forum once you are registered, what kind of help is available, and the rules of conduct on the forum. It also provides links to the source code for the examples in the book, errata, and other downloads. It is not a commitment to any specific amount of participation on the part of the authors, whose contribution to the AO remains voluntary and unpaid. We suggest you try asking the authors some challenging questions lest their interest stray!
According to research in cognitive science, the things people remember are things they discover during self-motivated exploration. Although no one at Manning is a cognitive scientist, we are convinced that for learning to become permanent it must pass through stages of exploration, play, and, interestingly, re-telling of what is being learned.
People understand and remember new things, which is to say they master them, only after actively exploring them. Humans learn in action. An essential part of an In Action guide is that it is example-driven. It encourages the reader to try things out, to play with new code, and explore new ideas.
There is another, more mundane, reason for the title of this book: They use books to do a job or solve a problem. They need books that allow them to jump in and jump out easily and learn just what they want, just when they want it.
They need books that aid them in action. The books in this series are designed for such readers. Saveur, published in Travel for pleasure was a relatively new phenomenon at the time and travel guides such as this one were popular, introducing both the tourist as well as the armchair traveler, to the inhabitants of other regions of France and abroad. This was a time when the dress codes of two regions separated by a few dozen miles identified people uniquely as belonging to one or the other.
The travel guide brings to life a sense of isolation and distance of that period and of every other historic period except our own hyperkinetic present. Dress codes have changed since then and the diversity by region, so rich at the time, has faded away.
It is now often hard to tell the inhabitant of one continent from another. Perhaps, trying to view it optimistically, we have traded a cultural and visual diversity for a more varied personal life. Or a more varied and interesting intellectual and technical life. We at Manning celebrate the inventiveness, the initiative, and the fun of the computer business with book covers based on the rich diversity of regional life two centuries ago brought back to life by the pictures from this travel book.
Each of the competing solutions has advantages and disadvantages, but they at least share the same scope and overall approach. For several years, persistence has been a hot topic of debate in the Java community. How do we achieve portability if every database management system has its own SQL dialect? Should we abandon SQL completely and adopt a new database technology, such as object database systems?
Hibernate is an open source ORM implementation. Hibernate is an ambitious project that aims to be a complete solution to the problem of managing persistent data in Java. Hibernate is an non-intrusive solution. This book is about Hibernate. This chapter explains why tools like Hibernate are needed. As this list of problems grows, it becomes apparent that we need tools and patterns to minimize the time we have to spend on the persistence-related code of our applications. Our discussion of the advantages and drawbacks of ORM gives you the full background to make the best decision when picking a persistence solution for your own project.
We understand that you probably want to try Hibernate right away. Almost all applications require persistent data. Persistence is one of the fundamental concepts in application development.
We start by taking a brief look at the technology and how we use it with Java. In fact, most of us use a relational database every day. Relational technology is a known quantity.
This alone is sufficient reason for many organizations to choose it. But to say only this is to pay less respect than is due. Relational technology provides a way of sharing data among different applications or among different technologies that form part of the same application the transactional engine and the reporting engine, for example. Relational technology is a common denominator of many disparate systems and technology platforms. Hence, the relational data model is often the common enterprise-wide representation of business entities.
Hibernate will automate many repetitive coding tasks, but your knowledge of persistence technology must extend beyond Hibernate itself if you want take advantage of the full power of modern SQL databases. Remember that the underlying goal is robust, efficient management of persistent data. The manipulation operations include insertion, update, and deletion. You retrieve data by executing queries with restriction, projection, and join operations including the Cartesian product.
For efficient reporting, you use SQL to group, order, and aggregate data in arbitrary ways. You can even nest SQL statements inside each other; this technique is called subselecting. You have probably used SQL for many years and are familiar with the basic operations and statements written in this language.
Still, we know from our own experience that SQL is sometimes hard to remember and that some terms vary in usage. SQL knowledge is mandatory for sound Java database application development. Also read An Introduction to Database Systems [Date ] for the theory, concepts, and ideals of relational database systems. The SQL itself might have been written by hand and embedded in the Java code, or it might have been generated on the fly by Java code.
You use the JDBC API to bind arguments to query parameters, initiate execution of the query, scroll through the query result table, retrieve values from the result set, and so on. Since the data access tasks are often so tedious, we have to ask: Are the relational data model and especially SQL the right choices for persistence in objectoriented applications? We answer this question immediately: There are many reasons why SQL databases dominate the computing industry.
Relational database management systems are the only proven data management technology and are almost always a requirement in any Java project.
However, for the last 15 years, developers have spoken of a paradigm mismatch. This mismatch explains why so much effort is expended on persistence-related concerns in every enterprise project. The paradigms referred to are object modeling and relational modeling, or perhaps object-oriented programming and SQL. The state of the object may be stored to disk and an object with the same state re-created at some point in the future. Almost all Java applications contain a mix of persistent and transient objects; hence we need a subsystem that manages our persistent data.
Modern relational databases provide a structured representation of persistent data, enabling sorting, searching, and aggregation of data. A database management system also provides data-level security. Then, instead of directly working with the rows and columns of an SQL result set, the business logic interacts with this object-oriented domain model and its runtime realization as a graph of interconnected objects.
This allows business logic to make use of sophisticated object-oriented concepts such as inheritance and polymorphism. For example, we could use wellknown design patterns such as Strategy, Mediator, and Composite [GOF ], all of which depend on polymorphic method calls. Now a caveat: Not all Java applications are designed this way, nor should they be.
Simple applications might be much better off without a domain model. Working with a tabular representation of persistent data is straightforward and well understood. However, in the case of applications with nontrivial business logic, the domain model helps to improve code reuse and maintainability significantly.
We focus on applications with a domain model in this book, since Hibernate and ORM in general are most relevant to this kind of application. Licensed to Jose Carlos Romero Figueroa The paradigm mismatch 7 If we consider SQL and relational databases again, we finally observe the mismatch between the two paradigms.
SQL operations such as projection and join always result in a tabular representation of the resulting data. This is quite different than the graph of interconnected objects used to execute the business logic in a Java application! These are fundamentally different models, not just different ways of visualizing the same model. With this realization, we can begin to see the problems—some well understood and some less well understood—that must be solved by an application that combines both data representations: Suppose you have to design and implement an online e-commerce application.
Looking at this diagram, you see that a User has many BillingDetails. You can navigate the relationship between the classes in both directions. To begin with, the classes representing these entities might be extremely simple: The paradigm mismatch will be visible when we add more entities and entity relationships to our application.
The updated object model is shown in figure 1. Not necessarily. The nicest solution might even be to create a user-defined Address Figure 1.
Basically, we have the choice of adding either several columns or a single column of a new SQL data type. This is clearly a problem of granularity. Adding a new data type to store Address Java objects in a single column to our database catalog sounds like the best approach.
The SQL standard supports user-defined data types, but very poorly. Our solution for this problem has several columns, of vendor-defined SQL types such as boolean, numeric, and string data types. Considering the granularity of our tables again, the USER table is usually defined as follows: In contrast, just two levels of granularity are visible at the level of the database: Many simple persistence mechanisms fail to recognize this mismatch and so end up forcing the less flexible representation upon the object model.
We describe the solution to this problem in chapter 3, section 3. We therefore have several methods to bill a user account. The most natural way to reflect this change in our object model is to use inheritance for the BillingDetails class. We might have an abstract BillingDetails superclass along with several concrete subclasses: CreditCard, DirectDebit, Cheque, and so on.
Each of these subclasses will define slightly different data and completely different functionality that acts upon that data. The UML class diagram in figure 1. We notice immediately that SQL provides no direct support for inheritance. Figure 1. This problem is now quite well understood in the community, and most solutions support approximately the same functionality.
The User class has an association to the BillingDetails superclass. This is a polymorphic association. At runtime, a User object might be associated with an instance of any of the subclasses of BillingDetails.
This feature is called polymorphic queries. We might explain this by saying that Java and other object-oriented languages is less strictly typed than SQL. Fortunately, two of the inheritance mapping solutions we show in chapter 3 are designed to accommodate the representation of polymorphic associations and efficient execution of polymorphic queries. The next aspect of the mismatch problem is the issue of object identity.
Was that a good choice? There are three ways to tackle this problem, two in the Java world and one in our SQL database. As expected, they work together only with some help.
Java objects define two different notions of sameness: Furthermore, some subtle difficulties are involved in implementing equals correctly for a persistent class.
Unfortunately, this decision makes it difficult to change a username: A surrogate key is a primary key column with no meaning to the user. For example, we might change our table definitions to look like this: These columns were introduced purely for the benefit of the relational data model.
How if at all should they be represented in the object model? In the context of persistence, identity is closely related to how the system handles caching and transactions. Different persistence solutions have chosen various strategies, and this has been an area of confusion. But first, we need to discuss the important concept of associations—that is, how the relationships between our classes are mapped and handled.
Is the foreign key in the database all we need? You remember that the User, Address, and BillingDetails classes are all associated. Unlike Address, BillingDetails stands on its own. BillingDetails objects are stored in their own table. Association mapping and the management of entity associations are central concepts of any object persistence solution.
Object-oriented languages represent associations using object references and collections of object references. In the relational world, an association is represented as a foreign key column, with copies of key values in several tables. There are subtle differences between the two representations. Object references are inherently directional; the association is from one object to the other. If an association between objects should be navigable in both directions, you must define the association twice, once in each of the associated classes.
In fact, navigation has no meaning for a relational data model, because you can create arbitrary data associations with table joins and projection.
Java associations may have many-to-many multiplicity. For example, our object model might have looked like this: You can see the multiplicity immediately by looking at the foreign key definition.
The following is a one-to-many association or, if read in that direction, a many-to-one: We can see them by considering a purely static view of the system. Perhaps the most difficult problem in object persistence is a dynamic.
In Java, when you access the billing information of a user, you call aUser. This is the most natural way to access object-oriented data and is often described as walking the object graph. You navigate from one object to another, following associations between instances.
The single most important thing to do to improve performance of data access code is to minimize the number of requests to the database. The most obvious way to do this is to minimize the number of SQL queries. Therefore, efficient access to relational data using SQL usually requires the use of joins between the tables of interest. The number of tables included in the join determines the depth of the object graph you can navigate. On the other hand, any object persistence solution provides functionality for fetching the data of associated objects only when the object is first accessed.
However, this piecemeal style of data access is fundamentally inefficient in the context of a relational database, because it requires execution of one select statement for each node of the object graph. This mismatch in the way we access objects in Java and in a relational database is perhaps the single most common source of performance problems in Java applications. Fortunately, Hibernate provides sophisticated features for efficiently fetching graphs of objects from the database, transparently to the application accessing the graph.
We discuss these features in chapters 4 and 7. This cost is often underestimated, and we think this is a major reason for many failed software projects. One of the major costs is in the area of modeling.
The relational and object models must both encompass the same business entities. The usual solution to this problem is to bend and twist the object model until it matches the underlying relational technology. This can be done successfully, but only at the cost of losing some of the advantages of object orientation. Keep in mind that relational modeling is underpinned by relational theory. Object orientation has no such rigorous mathematical definition or body of theoretical work.
A structural relationship must be specified at least three times Insert, Update, Select , adding to the time required for design and implementation. Recently, it has been fashionable to regard architectural or pattern-based models as a partial solution to the mismatch problem.
Hence, we have the entity bean component model, the data access object DAO pattern, and other practices to implement data access. These approaches leave most or all of the problems listed earlier to the application developer. To round out your understanding of object persistence, we need to discuss application architecture and the role of a persistence layer in typical application design. Persistence is one concern.
Other concerns are presentation, workflow, and business logic. Typical crosscutting concerns include logging, authorization, and transaction demarcation. A typical object-oriented architecture comprises layers that represent the concerns.
In this section, we first look at the layers of this type of architecture and why we use them. Layering also determines the kinds of interlayer dependencies that occur. The rules are as follows: A layer is dependent only on the layer directly below it.
Different applications group concerns differently, so they define different layers. A typical, proven, high-level application architecture uses three layers, one each for presentation, business logic, and persistence, as shown in figure 1. Code responsible for the presentation and control of page and screen navigation forms the presentation layer.
In some systems, this layer has its own internal representation of the business domain entities. In others, it reuses the model defined by the persistence layer.
We revisit this issue in chapter 3. If an SQL database is used, the database includes the relational schema and possibly stored procedures. There is much to be learned by looking at other approaches. After all, developers are familiar with relational database management systems, understand SQL, and know how to work with tables and foreign keys. However, the work involved in manually coding persistence for each domain class is considerable, particularly when multiple SQL dialects are supported.
This work usually ends up consuming a large portion of the development effort.
Furthermore, when requirements change, a hand-coded solution always requires more attention and maintenance effort.
So why not implement a simple ORM framework to fit the specific requirements of your project? The result of such an effort could even be reused in future projects. Excellent solutions already exist, not only the mostly expensive tools sold by commercial vendors but also open source projects with free licenses. Development of a reasonably full-featured ORM may take many developers months. For example, Hibernate is 43, lines of code some of which is much more difficult than typical application code , along with 12, lines of unit test code.
This might be more than your application. A great many details can easily be overlooked—as both the authors know from experience! Any ORM will handle the tedious common cases—the ones that really kill productivity. Serialization provides the ability to write a graph of objects the state of the application to a byte-stream, which may then be persisted to a file or database.
Another usage of serialization is to replicate application state across nodes in a cluster of machines. Why not use serialization for the persistence layer? Thus, the resulting byte-stream must be considered unsuitable for arbitrary search or aggregation.
Loading and overwriting an entire object graph in each transaction is no option for systems designed to support high concurrency.
Clearly, given current technology, serialization is inadequate as a persistence mechanism for high concurrency web and enterprise applications.
It has a particular niche as a suitable persistence mechanism for desktop applications. Many of the developer concerns will be addressed in the new EJB 3. Entity beans in the current EJB 2. The other solutions the DAO pattern, serialization, and ORM were distilled from many years of experience; they represent approaches that have stood the test of time.
Unsurprisingly, perhaps, EJB 2. A marginally more acceptable solution is container-managed persistence CMP , at least since some glaring deficiencies of the EJB 1. Here are six reasons why: In a sense, CMP forces your domain model into first normal form.
A reusable component should be a very coarse-grained object, with an external interface that is stable in the face of small changes to the database schema. Yes, we really did just claim that CMP entity beans are both too fine grained and too coarse grained!
Capabilities of CMP engines vary widely between vendors, and the mapping metadata is highly vendor-specific. Some projects have chosen Hibernate for the simple reason that Hibernate applications are much more portable between application servers.
We find that we must define additional data transfer objects DTOs, also called value objects when we need to transport data to a remote client tier. The use of fine-grained method calls from the client to a remote entity bean instance is not scalable; DTOs provide a way of batching remote data access. The DTO pattern results in the growth of parallel class hierarchies, where each entity of the domain model is represented as both an entity bean and a DTO.
This is a huge barrier to unit test driven development TDD. It even causes problems in applications that require batch processing or other offline functions. In the mids, new object-oriented database systems gained attention. An object-oriented database management system OODBMS is more like an extension to the application environment than an external data store.
An OODBMS usually features a multitiered implementation, with the backend data store, object cache, and client application coupled tightly together and interacting via a proprietary network protocol.
Object-oriented database development begins with the top-down definition of host language bindings that add persistence capabilities to the programming language. Hence, object databases offer seamless integration into the object-oriented application environment. Furthermore, a number of years after its release, and even in version 3. The ODMG is also no longer active. JDO was driven by members of the object-oriented database community and is now being adopted by object-oriented database products as the primary API, often in addition to the existing ODMG support.
You can use stored procedures even write them in Java using SQLJ and move the problem into the database tier. Political constraints long-term investments in SQL databases and the requirement for access to valuable legacy data call for a different approach. ORM may be the most practical solution to our problems.
Despite its long history the first research papers were published in the late s , the terms for ORM used by developers vary. The slash stresses the mismatch problem that occurs when the two worlds collide.
In this section, we first look at what ORM is. Then we enumerate the problems that a good ORM solution needs to solve. Finally, we discuss the general benefits that ORM provides and why we recommend this solution.
ORM, in essence, works by reversibly transforming data from one representation to another. This implies certain performance penalties. A further overhead at development time is the provision and management of metadata that governs the transformation. But again, the cost is less than equivalent costs involved in maintaining a hand-coded solution. And even ODMG-compliant object databases require significant classlevel metadata.
It describes a method for information analysis, used in database modeling, and is primarily supported by Microsoft Visio, a graphical modeling tool. Database specialists use it as a replacement or as an addition to the more popular entity-relationship modeling. An ORM solution consists of the following four pieces: Depending on the features or the particular implementation, the ORM runtime may also take on responsibility for issues such as optimistic locking and caching, relieving the application of these concerns entirely.
Pure relational The whole application, including the user interface, is designed around the relational model and SQL-based relational operations. This approach, despite its deficiencies for large systems, can be an excellent solution for simple applications where a low level of code reuse is tolerable. Direct SQL can be fine-tuned in every aspect, but the drawbacks, such as lack of portability and maintainability, are significant, especially in the long run. Applications in this category often make heavy use of stored procedures, shifting some of the work out of the business layer and into the database.
Light object mapping Entities are represented as classes that are mapped manually to the relational tables. This approach is extremely widespread and is successful for applications with a small number of entities, or applications with generic, metadata-driven data models.
Stored procedures might have a place in this kind of application. Medium object mapping The application is designed around an object model. SQL is generated at build time using a code generation tool, or at runtime by framework code.
Associations between objects are supported by the persistence mechanism, and queries may be specified using an object-oriented expression language. Objects are cached by the persistence layer. A great many ORM products and homegrown persistence layers support at least this level of functionality. Full object mapping Full object mapping supports sophisticated object modeling: Efficient fetching strategies lazy and eager fetching and caching strategies are implemented transparently to the application.
A number of commercial and open source Java ORM tools have achieved this level of quality. Are they fine-grained JavaBeans? Or are they instances of some coarser granularity component model like EJB? How transparent is the persistence tool?
Do we have to adopt a programming model and conventions for classes of the business domain? Or are there better approaches to metadata definition? There are several standard strategies. What about polymorphic associations, abstract classes, and interfaces? How do we map instances of particular classes to particular table rows? This is a problem of generic programming, and there are a number of solutions including source generation, runtime reflection, runtime bytecode generation, and buildtime bytecode enhancement.
Does the lifecycle of some objects depend upon the lifecycle of other associated objects? How do we translate the lifecyle of an object to the lifecycle of a database row? The application could do some of these things in memory. But efficient use of relational technology requires that this work sometimes be performed by the database. Efficient access to relational data is usually accomplished via table joins.
Object-oriented applications usually access data by navigating an object graph. Two data access patterns should be avoided when possible: In addition, two issues are common to any data-access technology. They also impose fundamental constraints on the design and architecture of an ORM: We discuss the way Hibernate manages these problems and data-access issues in chapters 3, 4, and 5, and we broaden the subject later in the book.
By now, you should be starting to see the value of ORM. In the next section, we look at some of the other benefits you gain when you use an ORM solution. An ORM implementation is a complex beast—less complex than an application server, but more complex than a web application framework like Struts or Tapestry. Why should we introduce another new complex infrastructural element into our system?
Will it be worth it? For the impatient, this section provides a quick summary of the most compelling benefits. On the contrary, we believe that Java developers must have a sufficient level of familiarity with—and appreciation of—relational modeling and SQL in order to work with ORM. ORM is an advanced technique to be used by developers who have already done it the hard way. To use Hibernate effectively, you must be able to view and interpret the SQL statements it issues and understand the implications for performance.
Productivity Persistence-related code can be perhaps the most tedious code in a Java application. No matter which application development strategy you prefer—top-down, starting with a domain model; or bottomup, starting with an existing database schema—Hibernate used together with the appropriate tools will significantly reduce development time.
Maintainability Fewer lines of code LOC makes the system more understandable since it emphasizes business logic rather than plumbing. Most important, a system with less code is easier to refactor. Of course, counting lines of code is a debatable way of measuring application complexity. However, there are other reasons that a Hibernate application is more maintainable. In systems with hand-coded persistence, an inevitable tension exists between the relational representation and the object model implementing the domain.
Changes to one almost always involve changes to the other. And often the design of one representation is compromised to accommodate the existence of the other.
What almost always happens in practice is that the object model of the domain is compromised. ORM provides a buffer between the two models, allowing more elegant use of object orientation on the Java side, and insulating each model from minor changes to the other.
The unspoken implication of the claim is that hand-coded persistence will perform at least as well in an actual application. But this implication will be true only if the effort required to implement at-least-as-fast hand-coded persistence is similar to the amount of effort involved in utilizing an automated solution.
The really interesting question is, what happens when we consider time and budget constraints? Given a persistence task, many optimizations are possible.
Most optimizations, however, are much easier to achieve with automated ORM. In a project with time constraints, hand-coded persistence usually allows you to make some optimizations, some of the time. Hibernate allows many more optimizations to be used all the time.
Furthermore, automated persistence improves developer productivity so much that you can spend more time hand-optimizing the few remaining bottlenecks. Finally, the people who implemented your ORM software probably had much more time to investigate performance optimizations than you have.
Did you realize that updating only the changed columns of a table can be significantly faster for some databases but potentially slower for others?
In your handcrafted solution, how easy is it to experiment with the impact of these various strategies? If the tool supports a number of different databases most do , then this confers a certain level of portability on your application. In addition, database independence helps in development scenarios where developers use a lightweight local database but deploy for production on a different database. Object persistence means that individual objects can outlive the application process; they can be saved to a data store and be re-created at a later point in time.
A good solution for this problem is ORM, which is especially helpful if we consider richly typed Java domain models.
A domain model represents the business entities used in a Java application. In a layered system architecture, the domain model is used to execute business logic in the business layer in Java, not in the database. This business layer communicates with the persistence layer beneath in order to load and store the persistent objects of the domain model.
ORM is the middleware in the persistence layer that manages the persistence. We and many others may have to rethink everything we know about SQL, persistence API standards, and application integration. Instead, our program will store newly created objects in the database, update them, and perform queries to retrieve them from the database. This chapter will form the basis for the subsequent chapters. The objective of our sample application is to store messages in a database and to retrieve them for display.
The application has a simple persistent class, Message, which represents these printable messages. Our Message class is shown in listing 2. Listing 2. The identifier attribute allows the application to access the database identity—the primary key value—of a persistent object.
If two instances of Message have the same identifier value, they represent the same row in the database. You may have noticed that all attributes of the Message class have JavaBean-style property accessor methods. The class also has a constructor with no parameters. The persistent classes we use in our examples will almost always look something like this. It prints "Hello World" to the console.
Our persistent class can be used in any execution context at all—no special container is needed. It results in the execution of something similar to the following SQL: Actually, the id property is special: The value is assigned to the Message instance by Hibernate when save is called.
The next example retrieves all messages from the database, in alphabetical order, and prints them: This query is internally translated into the following SQL when find is called: To allow this magic to occur, Hibernate needs more information about how the Message class should be made persistent. This information is usually provided in an XML mapping document. You can easily write and maintain it by hand. Whichever method you choose, Hibernate has enough information to completely generate all the SQL statements that would be needed to insert, update, delete, and retrieve instances of the Message class.
You no longer need to write these SQL statements by hand. Some have suggested a movement away from XML metadata, back to plain Java code. Although we applaud this suggestion for some problems, ORM represents a case where text-based metadata really is necessary. Hibernate has sensible defaults that minimize typing and a mature document type definition that can be used for auto-completion or validation in editors.
You can even automatically generate metadata with various tools. Similarly, you can see that the new message was made persistent when a reference was created from the first message. This feature is called cascading save: Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user.
This feature is called transactional write-behind. A major objective of API design is to keep the interfaces between software components as narrow as possible. Figure 2. We show the business layer above the persistence layer, since the business layer acts as a client of the persistence layer in a traditionally layered application.
The Hibernate interfaces shown in figure 2. They include Session, Transaction, and Query. These interfaces are implemented by application infrastructure code if necessary. JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate.
You can find most of these interfaces in the package net. Using these interfaces, you can store and retrieve persistent objects and control transactions.
Session interface The Session interface is the primary interface used by Hibernate applications. An instance of Session is lightweight and is inexpensive to create and destroy. This is important because your application will need to create and destroy sessions all the time, perhaps on every request. Hibernate sessions are not threadsafe and should by design be used by only one thread at a time. The Hibernate notion of a session is something between connection and transaction.
It may be easier to think of a session as a cache or collection of loaded objects relating to a single unit of work. Hibernate can detect changes to the objects in this unit of work. Note that a Hibernate session has nothing to do with the web-tier HttpSession. When we use the word session in this book, we mean the Hibernate session.
We sometimes use user session to refer to the HttpSession object. We describe the Session interface in detail in chapter 4, section 4. Compared to the Session interface, this object is much less exciting. The SessionFactory is certainly not lightweight! There is typically a single SessionFactory for the whole application—created during application initialization, for example. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work only if class and collection mappings specify that this second-level cache is desirable.
Licensed to Jose Carlos Romero Figueroa Understanding the architecture 39 Configuration interface The Configuration object is used to configure and bootstrap Hibernate. The application uses a Configuration instance to specify the location of mapping documents and Hibernate-specific properties and then create the SessionFactory.
Section 2. Hibernate applications may choose not to use this interface, instead managing transactions in their own infrastructure code. This helps to keep Hibernate applications portable between different kinds of execution environments and containers. Transactions and the Transaction interface are explained in chapter 5. Query and Criteria interfaces The Query interface allows you to perform queries against the database and control how the query is executed.
A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query. The Criteria interface is very similar; it allows you to create and execute objectoriented criteria queries.
To help make application code less verbose, Hibernate provides some shortcut methods on the Session interface that let you invoke a query in one line of code. We describe the features of the Query interface in chapter 7.
The Lifecycle and Validatable interfaces allow a persistent object to react to events relating to its own persistence lifecycle.
The Hibernate team was heavily influenced by other ORM solutions that have similar callback interfaces. The Interceptor interface was introduced to allow the application to process callbacks without forcing the persistent classes to implement Hibernate-specific APIs.
Implementations of the Interceptor interface are passed to the persistent instances as parameters. A Hibernate Type object maps a Java type to a database column type actually, the type may span multiple columns. All persistent properties of persistent classes, including associations, have a corresponding Hibernate type.
This design makes Hibernate extremely flexible and extensible. There is a rich range of built-in types, covering all Java primitives and many JDK classes, including types for java. Currency, java. Calendar, byte, and java. Even better, Hibernate supports user-defined custom types. You can use this feature to allow commonly used application classes such as Address, Name, or MonetaryAmount to be handled conveniently and elegantly.