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 ). Although native types may be easier to use in syntaxLongOrJava. Lang. LongThere is no difference ,.

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.Org. hibernate. Connection. connectionprovider

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. 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.

Understanding SessionFlushing)

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 the layer-3 structure, consider using Saveorupdate ()

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.Session. Update ()OrSession. saveorupdate ()To update the object's persistent state.

In a two-layer structure, consider disconnecting the session.

To achieve optimal scalability, database transactions should be as short as possible. However, programs often need to implement long-running "application transaction", which contains an atomic operation from the user's point of view. This application transaction may span multiple cycles from user requests to feedback. Use the unmanaged object (the object that is detached from the session), or remove the hibernate session from the JDBC connection in a two-layer structure, and connect it the next time you need to use it. Never use a session in multiple application transactions. Otherwise, your data may expire.

Do not regard exceptions as recoverable

This is even more important than "best practice", which is "essential knowledge ". Rollback is required when an exception occurs.Transaction, 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 ().

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.

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 .)

Use business-related key values Equals ()And Hashcode ().

If you compare objects outside the session, you must implementEquals ()AndHashcode (). Within the session, Java's object recognition mechanism can be ensured. If you have implemented these methods, do not use the database (primary key) for identification! The instantaneous object does not have an (database) 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 ()To compare the sets (delayed loading should be considered), and be careful with other classes that may be proxied.

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.

 

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.