Hibernate _ note 17 (persistent entity class)

Source: Internet
Author: User

Compiling POJO and persistence object Hibernate works best with the domain model implemented by POJO. Hibernate imposes a few necessary conditions on the Implementation of Domain Models and is also the best practice for POJO implementation. Therefore, most POJO can be compatible with Hibernate without any changes. The prerequisites for Hibernate are almost the same as those for EJB3.0 object classes. Therefore, POJO can be easily identified by annotations and an EJB3.0-compatible entity can be created.
POJO declares the business methods that define the behavior and the attributes that indicate the status. Some attributes indicate the association with other custom POJO.
POJO Implementation of the User class

Public class User implements Serializable {private static final long serialVersionUID =-7834734244153955773l; private String username; private Address address; public User () {super ();} public User (String username, address address) {super (); this. username = username; this. address = address;} public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public Address getAddress () {return address;} public void setAddress (Address address Address) {this. address = address;} // calculation price public MonetaryAmount calcShippingCosts (Address fromLocation) {return null ;}}
Hibernate does not require the persistence class to implement Serializable (Serializable ). However, when an object is stored in an HttpSession or passed by RMI value, serialization is required. Classes can be abstract. If necessary, non-persistent classes can be extended.
Unlike the JavaBeans specification, it does not require a specific constructor, while Hibernate (and JPA) requires that each persistence class has a non-argument constructor. In this constructor, Hibernate uses Java Reflection API to call persistence classes to instantiate objects. Constructors can be non-public, but must at least be package-visible, if the runtime is to be used for performance optimization. Proxy generation also requires that this class not be declared final (and there is no final method ).
The JavaBean Specification defines guidelines for naming these methods, allowing common tools (such as Hibernate) to easily discover and manipulate attribute values. The get method name starts with get, followed by the attribute name (uppercase). set the method name to the set switch, and similarly follow the attribute name. You can use Is instead of Get to obtain the Boolean attribute.
Implement POJO Association
You use attributes to express the associations between POJO classes and use access methods to navigate from an object to an object at runtime.
Consider the associations defined by the Category class, as shown in 3-3.
Like all graphs, attributes related to association are omitted (we call them parentCategory and childCategories) because they will mess up the graphs. These attributes and methods for operating their values are also known as the scaffold code (scaffolding code ).
This is a one-to-multiple associated scaffolding code of the Category class:
Public class Category {private String name; // type name private Category parentCategory; // parent type private Set
 
  
ChildCategories = new HashSet
  
   
(); // Subtype public Category () {super ();} public Category (String name, Category parentCategory, Set
   
    
ChildCategories) {super (); this. name = name; this. parentCategory = parentCategory; this. childCategories = childCategories;} public String getName () {return name;} public void setName (String name) {this. name = name;} public Category getParentCategory () {return parentCategory;} public void setParentCategory (Category parentCategory) {this. parentCategory = parentCategory;} public Set
    
     
GetChildCategories () {return childCategories;} public void setChildCategories (Set
     
      
ChildCategories) {this. childCategories = childCategories ;}}
     
    
   
  
 
Managing links between two Category instances is more difficult than setting a foreign key value in a database field. Based on our experience, developers often do not know this complexity from a network object model that contains bidirectional references. We will discuss this issue step by step.
The basic process of adding a sub-Category to a parent Category looks like this:
Category aParent = new Category();Category aChild = new Category();aChild.setParentCategory(aParent);aParent.getChildCategories().add(aChild);
Note: The managed relationship in Hibernate-Hibernate does not manage persistent associations. If you want to perform an association, you must write exactly the same code as if there is no Hibernate. If the association is bidirectional, both sides of the relationship must be considered. The programming model (such as EJB2.1 entity bean) disrupts this behavior by introducing the container-managed relationship-if one side is modified by the application, the container automatically changes the other side of the relationship. This is one of the reasons why EJB2.1 Entity bean Code cannot be reused outside the container. The EJB3.0 Association is transparent, just like in Hibernate. If you do not understand the behavior associated with Hibernate, ask yourself: "What will I do if there is no Hibernate ?" Hibernate does not change the general Java semantics.
It is a good idea to add a convenient method to the Category class for these operations. This allows reuse, helps ensure correctness, and ultimately ensures data integrity:
public void addChildCategory(Category childCategory) {if (null == childCategory)throw new IllegalArgumentException("Null child category");if (null != childCategory.getParentCategory()) {childCategory.getParentCategory().getChildCategories().remove(childCategory);childCategory.setParentCategory(this);this.childCategories.add(childCategory);}}
The addChildCategory () method not only reduces the code lines when processing the Category object, but also enhances cardinality ). It avoids errors generated when one of the two required actions is missed. If possible, always groups that provide such operations for the association.
You can set the setChildCategories () method to private because you want addChildCategory () to become the only externally visible memory method (mutator method) in the subclass (and possibly add the removeChildCateogry () method, or delete it ,.
There is a different relationship between the Category and Item classes: a bidirectional multiple-to-Multiple Association, as shown in 3-4.
For many-to-many associations, both sides use the set value attribute. Add new attributes and methods for accessing the Item Relationship to the Category class:
Public class Category {private String name; // type name private Category parentCategory; // parent type private Set
 
  
ChildCategories = new HashSet
  
   
(); // Subtype private Set
   
    
Items = new HashSet
    
     
(); // Product list}
    
   
  
 
The code of the Item class (the other side of multiple-to-Multiple Association) is similar to the code of the Category class. Adds a set attribute, a standard access method, and a method to simplify link management.
public class Item implements Serializable {private static final long serialVersionUID = 2473606759362725264L;private String name;private String description;private BigDecimal initialPrice;private BigDecimal reservePrice;private Date startDate;private Date endDate;private ItemState state;private Date approvalDatetime;private Set
 
   categories = new HashSet
  
   ();public void addCategory(Category category) {if (null == category)throw new IllegalArgumentException("Null category");category.getItems().add(this);categories.add(category);}}
  
 
The addCategory () method is similar to the addChildCategory () convenient method of the Category class. It is used by the client to operate the link between Item and Category. To improve readability, the convenience methods will not be displayed in subsequent code samples, and you will add them based on your preferences.
Convenience methods for association processing are not the only way to improve the implementation of Domain Models. You can also add the logic to your access method.
Add logic to access method
One of the reasons we like to use the access methods in the JavaBean style is that they provide encapsulation: the internal hidden implementation of an attribute can be changed to a public interface without any change.
For example, if the database saves the User NAME as a single name column, but the User class has the firstname and lastname attributes, you can add the following persistent NAME attributes to the class:
Public class User implements Serializable {private static final long serialVersionUID =-7834734244153955773l; private String firstname; private String lastname ;//... public String getName () {return firstname + lastname;} public void setName (String name) {// StringTokenizer is an application class used to separate strings. StringTokenizer t = new StringTokenizer (name, ""); this. firstname = t. nextToken (); this. lastname = t. nextToken ();}//...}
Later, you will understand that Hibernate custom types are a better way to deal with multiple such cases. However, there are also advantages if there are multiple options.
The access method can also be verified. For example, in the following example, the setFirstName () method verifies the capital Name:
public class User implements Serializable {private static final long serialVersionUID = -7811634244303955773L;private String firstname;// ...public String getFirstname() {return firstname;}public void setFirstname(String firstname) throws InvalidNameException {if (!StringUtil.isCapitalizedName(firstname))throw new InvalidNameException(firstname);this.firstname = firstname;}}
Another problem to consider is dirty checking. Hibernate automatically detects changes in the object state to synchronize the updated state with the database. Returning a different object from the get method is usually safer than passing the object from Hibernate to the set method. Hibernate compares objects by value-not by Object Identity-to determine whether the persistence status of an attribute needs to be updated. For example, the following method does not cause unnecessary SQL UPDATE ):
public String getFirstname() {return new String(firstname);}
Another important exception is that the set is compared by identity! For an attribute mapped to a persistent set, you should return a set instance that is exactly the same as that passed by Hibernate to the Set Method in the get method. If no, Hibernate updates the database. Even if no updates are required, the State stored in the memory will be synchronized with the database each time.
Finally, you must know how to handle exceptions in the access method, if you configure Hibernate to use these methods when loading and storing instances. If a RuntimeException is thrown, the current transaction is rolled back. You need to handle this exception by yourself. If an application exception is thrown, Hibernate will package the exception in a RuntimeException.
Any ORM solution in XML should provide a human-readable, easy-to-Manually-edit ing format, not just a GUI ing tool. Currently, the most popular Object/link metadata format is XML. The ing documents written in or containing XML are lightweight, human-readable, easy to operate through the version control system and text editor, and can be customized during deployment.
But is XML-based Metadata really the best way?
In our opinion, there are three reasons:
1) metadata-based solutions are often improperly applied. Metadata is not as flexible or easy to maintain as simple Java code.
2) Many existing metadata formats are not designed to be readable and easy to manually edit.
3) Good XML editors, especially in IDE, are not as common as good Java coding environments.
You cannot avoid metadata requirements in ORM. However, Hibernate fully recognizes typical metadata issues during design. Hibernate's XML Metadata format is very readable and defines useful default values. If no attribute value exists, the default value is determined by reflection on the mapped class. Hibernate also contains a fully documented DTD. In the end, IDE's support for XML has been improved recently. Modern IDE provides dynamic XML verification and even provides an automatic feature.
XML ing file of the Category class:
 
  
   
    
   
   
  
 
In this example, the set and association ing are intentionally omitted. Association, especially set ing, is more complex, so we will return to this topic later.

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.