Proficient in Hibernate: object relationship ing BASICS (1)

Source: Internet
Author: User

1. attributes and access methods of persistence classes
(1) Introduction to persistence

In Hibernate, there are two access methods for persistence classes: one is a Java application and the other is Hibernate. It is worth noting that Java applications cannot access getXXX () and setXXX () of the private type of the persistence class, but Hibernate does not have such restrictions.

(2) Basic type attributes and packaging type attributes

Java has eight basic types: byte, short, char, int, long, float, double, boolean. Corresponding Java provides eight packaging types: Byte, Short, character, Integer, Long, Float, Double, Boolean. The basic type and packaging type can be converted as follows:

 
 
  1. Double prD = 1;
  2. // Convert the Basic double type to the Double packaging type
  3. Double wrD = new Double (prD );
  4. // Convert the Double packaging type to the double basic type
  5. PrD = wrD. doubleValue ();

Both types of Hibernate are supported.

(3) Add the program logic to the persistent class access method

(A) Add the program logic to the getName () and setName () Methods of the Customer class

Assume that the Customer class has the firstname and lastname attributes, but there is no name attribute, while the database MERs table only has the NAME field. After Hibernate obtains the NAME field value of the MERs table from the database, it will call the setName () method. At this time, Hibernate should use the setName () method to automatically set the firstname attribute and lastname. Therefore, additional program logic must be added to the setName () method.

 
 
  1.  public String getName(){  
  2.    return firstname+ " "+lastname;  
  3. }  
  4.  
  5. public void setName(String name){  
  6.   StringTokenizer t=new StringTokenizer(name);  
  7.   firstname=t.nextToken();  
  8.   lastname=t.nextToken();  

In the ing file, you can directly map the name without ing firstname.

 
 
  1. <property name="name" column="NAME"> 

Although the name attribute is not defined in the Customer class, Hibernate does not directly access the name attribute, but uses the getName () and setName () methods. As long as the name attribute is mapped to the Customer. hbm. xml file, the HQL statement can access:

 
 
  1. Query query=seesion.createQuery("from Customer as c where c.name='Tom'"); 

However, if you set the name attribute in the Customer. hbm. xml file:

 
 
  1. <property name="name" column="NAME" access="field"> 

The program directly accesses the name attribute in the Customer instance, and an exception occurs.

(B) add the program logic to the setOrders () method of the Customer class

Assume that the Customer class has an avuplice attribute, indicating the average price of the Order. The value is the average value of the price of the Order object associated with it. There is no AVG_PRICE field in the MERs table. You can perform the following operations:

 
 
  1. Public Double getavuplice (){
  2. Return this. avuplice;
  3. }
  4. Private void setavuplice (Double avuplice ){
  5. This. avuplice = avuplice;
  6. }
  7. Public Double getTotalPrice (){
  8. Return this. totalPrice;
  9. }
  10. Private void setTotalPrice (Double totalPrice ){
  11. This. totalPrice = totalPrice;
  12. }
  13.  
  14. Public void setOrders (Set orders ){
  15. This. orders = orders;
  16. CalculatePrice ();
  17. }
  18. Public Set getOrders (){
  19. Return orders;
  20. } // Define it as a Set
  21. Private void calculatePrice (){
  22. Double avgpice = 0.0;
  23. Double totalprices = 0.0;
  24. Int count = 0;
  25. /Calculate all prices in orders iteratively
  26. If (getOrders ()! = Null ){
  27. Iterator iter = getOrders (). iterator ();
  28. While (iter. hasNext ()){
  29. Double orderPrice = (Order) iter. next (). getPrice ();
  30. TotalPrice + = orderPrice;
  31. Count ++;
  32. }
  33. // Set the price for the order from the calcualted value
  34. Avuplice = totalPrice/count;
  35. Setavuplice (new Double (avuplice ));
  36. }
  37. }

In the Customer. hbm. xml file, you do not need to map avuplice, because Hibernate does not directly access the avuplice attribute, nor call getavuplice () and setavuplice ().

(C) Add the data verification logic to the setSex () method of the Customer class.

Data Verification logic can also be added to access methods of persistence classes.

 
 
  1. public char getSex(){  
  2.    return this.sex;  
  3.  }  
  4.  public void setSex(char sex){  
  5.      if(sex!='F' && sex!='M'){  
  6.        throw new IllegalArgumentException("Invalid Sex");  
  7.      }  
  8.      this.sex =sex ;  
  9.  } 

(4) set derived attributes
Not all attributes of the persistence class directly match the fields in the table. Some attributes of the persistence class can be obtained at runtime. These attributes are called derived attributes. As in the previous avuplice attribute, this solution involves two steps:

  • Do not map avuplice attributes in the ing File
  • Add the program logic to the setOrders () method of the Customer class and assign values to the avuplice attribute automatically.

In addition to this method to set derived attributes, you can also solve the problem as follows:

Use the formula attribute of the <property> element. The formula attribute is used to set an SQL expression. Hibernate calculates the value of the derived attribute based on it. Take the totalPrice attribute of the Customer class as an example:

 
 
  1. <property name="totalPrice" formula="(select sum(o.PRICE) from ORDERS o where o.CUSTOMER_ID=ID)"/> 

When Hibernate queries a Customer object from a database, if totalPrice is queried, that is:

 
 
  1. select totalPrice from CUSTOMERS; 

After the formula attribute is used, the preceding query statement is automatically replaced:

 
 
  1. select (select sum(o.PRICE) from ORDERS o where o.CUSTOMER_ID=1) from CUSTOMERS; 

If the query result of the clause is null, the preceding statement will be abnormal. Solution: Define the totalPrice attribute as the Double packaging type.

(5) control insert and update statements

In the initialization phase, Hibernate defines the following SQL statements for all persistence classes based on the ing information of the ing file.

"?" In the preceding SQL statement Represents the parameter in JDBC PreparedStatement. These SQL statements are stored in the built-in cache of SessionFactory. When the Session save (), update (), delete (), load (), and get () methods are executed, find the predefined SQL statement from the cache, and then bind the specific parameter value to the SQL statement.


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.