Hibernate Best Practices

Source: Internet
Author: User
Design and use a fine-grained persistent class<Component>To implement ing.

Use oneAddressPersistent class EncapsulationStreet,Suburb,State,PostcodeThis will facilitate code reuse and simplify code refactoring.

Declare the identifier attribute for a persistent class.

The identifier attribute in Hibernate is optional, but there are many reasons to explain that you should use the identifier attribute. We recommend that the identifier be "artificial" (automatically generated, without business meaning) and not a basic type. For maximum flexibility, useJava. Lang. LongOrJava. Lang. String

Natural Primary Key Identifier

For all dead bodies using the natural primary key flag<Natural-ID> to implementEquals () andThe hashcode () method is used to compare the tree type.

Write a ing file for each persistent class

Do not write all persistent class mappings to a large file. SetCom. eg. fooMapCOM/EG/Foo. HBM. xmlThis is particularly meaningful in the team development environment.

Load the ing file as a resource

Deploy the ing files and Their ing classes together.

Consider placing the query string outside the program

If your query calls non-ANSI standard SQL functions, this practical experience applies to you. Placing the query string in the ing file can make the program more portable.

Bind Variable

Like in JDBC programming, placeholders should always be used "? "To replace the extraordinary value. Do not use the string value in the query to construct the extraordinary value! A better way is to use named parameters in the query.

Do not manage JDBC connections on your own

Hibernate allows applications to manage JDBC connections by themselves, but it should be used as a final solution. If you cannot use the built-in connections providers of hibernate, consider implementing it yourself.Net. SF. hibernate. Connection. connectionprovider

Consider using the custom type)

Net. SF. hibernate. usertype. Suppose you have a Java type from some class libraries that need to be persisted, but this class does not provide the access method required for the ing operation. So you should consider implementingNet. SF. hibernate. usertypeInterface. In this way, the program code can be written more freely without the need to consider the mutual conversion between classes and hibernate types.

Use hard-coded JDBC in performance bottlenecks

In some systems with strict performance requirements, it may be better to directly use JDBC for some operations (such as batch update and batch delete), but please firstClarifyWhether this is a bottleneck, and do not assume that JDBC will be faster. If you do need to use JDBC directly, you 'd better open a hibernateSessionThenSessionObtain the connection. In this way, you can still use the same transaction policy and the underlying connection provider.

UnderstandingSessionFlushing)

Sessions synchronize the persistent state to the database from time to time. If this operation is performed too frequently, the performance will be affected. Sometimes you can minimize unnecessary flushing operations by disabling automatic flushing, or further change the query and other operations in a special transaction.

In a three-tier architecture, consider using the detached object

When using the servlet/Session Bean architecture, you need to use session to read persistent objects and pass value objects to the servlet/jsp layer. Use a new session for each request. UseSession. Merge ()OrSession. saveorupdate () method to synchronize objects with databases.

In a two-tier architecture, consider using a long persistent Context

To improve performance, database transactions should be as short as possible. However, in actual business, you often need to implement long-running application transactions. Each view of each user uses a simple unit of work. Application transactions span the response cycles of Multiple customer requests. Usually, the detached object is used to implement application transactions. In a two-tier architecture, the most appropriate method is to maintain a single session in the entire application transaction ), then, close the JDBC connection at the end of each request, and then reconnect them in the concurrent request.

Do not regard exceptions as recoverable

This is even more important than "best practice", which is "essential knowledge ". Roll back when an exception occursTransaction, DisableSession. If you don't do this, Hibernate won't be able to ensure that the memory status accurately reflects the persistent state. Do not useSession. Load ()To determine whether an object instance with a given identifier exists in the database.Find (). Of course, there are some exceptions, suchStaleobjectstateexceptionAndObjectnotfoundexception.

Supplement: runtime and compilation exceptions

The exception during compilation must be caught in the Code; otherwise, the compilation fails.

When an exception occurs, you can catch it explicitly.

Lazy fetching is preferred for Association

Exercise caution when using the eager (outer-join) fetching ). For most associations of persistent objects without JVM-level cache, use a proxy (proxies) or a set with delayed loading attributes (lazy collections ). For the association of cached objects, especially when the cache hit rate is very high, you should useOuter-join = "false"To explicitly disable eager fetching. For special scenarios where outer-join fetch is applicable, useLeft join.

Use oPen session in view modeOr disciplinedAssembly phaseEliminate problems arising from Data Acquisition

Hibernate allows the development of lengthy data transmission objects (DTO ). In the traditional EJB architecture, using dtos has two purposes: first, they solve the problem that the entity bean does not implement the serializable interface; second, when they provide data for the presentation layer, the DTO object shields some associated operations between objects. Hibernate ruled out the first case. However, you still need a connection phase (imagine that the business logic strictly defines the data objects used by the presentation layer). Otherwise, the rendering phase of the presentation layer may be passed to the presentation layer. This is not the limitation of hibenate. It is the basic principle to ensure access to transactional data.

Consider abstracting hibernate code from business logic code

Hides the hibernate data access code behind the interface.DaoAndThread Local sessionMode. Through hibernateUsertypeYou can even use hard-coded JDBC to persist the classes that are supposed to be persisted by hibernate. (This recommendation is more suitable for applications with a large enough size, but not applications with only five tables .)

Do not use external connection ing

A good real pair-to-pair connection is rare. Most of the time, additional information needs to be stored in the chain table. For this reason, it is more wise to use two one-to-one connections to replace the link class of an intermediary. In fact, more connections should be one-to-one and two-to-one. Be careful when using other types of connections, if there are other types of connections in the design, review them carefully to confirm that they are required.

Use business-related key valuesEquals ()AndHashcode ().

If you compare objects outside the session, you must implementEquals ()AndHashcode (). Within the session, Java object recognition can be trustworthy. If you have implemented these methods, do not use database identification again! The instantaneous object does not have an Identifier value. hibernate will assign it a value when the object is saved. If the object is saved in the Set, the hash code changes and the offer is violated. To achieve business-related key value writingEquals ()AndHashcode (), You should use the unique combination of class attributes. Remember, this key value must be stable and unique only when the object is inside the set. It is not required throughout its lifecycle (it does not need to achieve the stability of the database primary key ). NeverEquals ()Sets are used in comparison (delayed loading should be considered), and these associated classes may be used as proxies.

Do not use weird connection ing

Many-to-many connections are rarely used. Most of the time, you need to save additional information in the "connection table. In this case, it is better to use two one-to-multiple connections pointing to the intermediary class. In fact, we think that the vast majority of connections are one-to-many and one-to-one. You should be cautious about using other connection styles and ask yourself if you really need to do so.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.