Part 7 best practices of 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. Identifier Properties). 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 keysIdentifies 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 classDo 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 resourceDeploy the ing files and Their ing classes together. Consider placing the query string outside the programIf 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 VariableLike 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 ownHibernate 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 bottlenecksSome 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 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. It is common to use a takeover object (an object that is out of the session) to implement application transactions. Or, especially in the two-layer structure, remove the hibernate session from the JDBC connection and connect it the next time you need it. Never use a session in multiple application transactions. Otherwise, your data may expire. Do not regard exceptions as recoverableThis is even more important than "best practice", which is "essential knowledge ". When an exception occurs, you must roll back the transaction and close the session. If you don't do this, Hibernate won't be able to ensure that the memory status accurately reflects the persistent state. In particular, do not use session. Load () to determine whether an object instance with a given identifier exists in the Database. You should use session. Get () or perform a query. Lazy fetching is preferred for AssociationUse 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 codeHides 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 .) Not to 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 preferredOne-way Association is more difficult to query. In large applications, almost all associations must be in two-way navigation in queries. For original content conversion, please note 【
Http://] video companion PPT, video address [hibernate4 practices-exclusive video course]

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