TIPS: 17 skills for developing Hibernate4

Source: Internet
Author: User

Design a fine-grained persistent class and use <component> for ing.
For example, using an Address persistent class to encapsulate street, suburb, state, and postcode will facilitate code reuse and simplify code refactoring.

Declare the identifier property (identifier properties) for the 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 ).

Use natural keys
Identifies the natural keys for all objects and maps them with <natural-id>. Implement equals () and hashCode (), in which the attributes that constitute the natural key are compared.

Write a ing file for each persistent class
Do not write all persistent class mappings to a large file. Ing com. eg. Foo to com/eg/Foo. hbm. xml makes sense 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 org. hibernate. connection. ConnectionProvider by yourself.

Consider using the custom type)
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. You should consider implementing the org. hibernate. UserType interface. 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
Some of the performance requirements in the system are very strict, and some operations may be better to use JDBC directly. However, please first confirm that this is indeed a bottleneck, and do not take it for granted that JDBC will be faster. If you do need to directly use JDBC, you 'd better open a Hibernate Session and obtain the connection from the Session. In this way, you can still use the same transaction policy and the underlying connection provider.

Understanding Session cleansing (flushing)
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 disable automatic flushing to minimize unnecessary flushing operations, or further change the query and other operations in a specific transaction.

In a three-tier structure, consider using a managed object (detached object)
When using a servlet/session bean architecture, you can transfer the loaded persistent objects back and forth between the session bean layer and the servlet/JSP layer. Use a new session to serve each request. Use Session. merge () or Session. saveOrUpdate () to synchronize with the database.

In a two-layer structure, long persistence contexts is considered ).
To achieve optimal scalability, Database transactions should be as much as possible

Short. However, the program often needs to implement the "Application transaction (

Transaction) ", contains an atomic operation from the user's point of view. This application transaction

It may span multiple cycles from user requests to feedback. Use an unmanaged object (a session-separated pair

Is common. Or, especially in the two-layer structure

The Session is detached from the JDBC connection and connected again when it needs to be used next time. Never put

Session is used in multiple Application transactions. Otherwise, your data

It may expire.

Do not regard exceptions as recoverable
This is even more important than "best practice", which is "essential knowledge ". When an exception occurs

The Transaction must be rolled back to close the Session. If you do not,

Hibernate cannot ensure that the memory status accurately reflects the persistent status. Do not use

Session. load () to determine whether an object instance with a given identifier exists in the database.

Use Session. get () or perform a query.

Lazy fetching is preferred for Association
Use the eager fetching with caution ). For associations, if the target is a class that cannot completely cache all instances in the second-level cache, you should use a proxy (proxies) and/or a set with the delayed loading attribute (lazy collections ). If the target can be cached, especially when the cache hit rate is very high, lazy = "false" should be used to explicitly disable eager fetching. If special cases are suitable for join fetch, use left join fetch in the query.

Use the open session in view mode, or execute a strict assembly phase (assembly phase) policy to avoid the problem of re-capturing data.

Hibernate frees developers from the tedious Data Transfer Objects (DTO ). In the traditional EJB structure, DTO has a dual role: first, they solve the problem that entity beans cannot be serialized; secondly, they implicitly define an Assembly period during which, all the data required in the view layer is captured, centralized to DTO, and then controlled to be mounted to the presentation layer. Hibernate ended the first role. However, unless you are ready to maintain an open persistent context (session) throughout the rendering process, you still need an Assembly period (imagine, your business method has a strict contract with your presentation layer, and data is always placed in managed objects ). This is not a limitation of Hibernate! This is the basic requirement for achieving secure transactional data access.

Consider abstracting Hibernate code from business logic code
Hides the Hibernate data access code behind the interface and uses the DAO and Thread Local Session modes in combination. Through Hibernate's UserType, you can even use hard-coded JDBC to persist classes that are supposed to be persist by Hibernate. (This recommendation is more suitable for applications with a large enough size, but not applications with only five tables .) 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.

Two-way Association preferred
One-way Association is more difficult to query. In large applications, almost all associations must be in two-way navigation in queries.


Author: chromeplugin

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.