Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Hibernate3.6 Application

2025-03-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What this article shares with you is an example analysis of the Hibernate3.6 application. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

Hibernate is a very famous object-relational mapping tool that uses a version of Hibernate3.6. In this paper, through the establishment of a project to guide you to learn hibernate, have an understanding of hibernate. It doesn't matter that some codes and concepts are not clear, which will be introduced later.

First create a Web Project, and then add the relevant jar package under WEB-INF/lib. The project structure is shown in figure 1 below. The jar package is described as follows:

Figure 1

The corresponding jar package under the hibernate-distribution-3.6.0.Final-dist\ hibernate-distribution-3.6.0.Final\ lib\ required directory:

Conversion of antlr-2.7.6.jar:HQL-- > SQL

Collection tools of commons-collections-3.1.jar:Apache

Dom4j.jar: parsing XML documents

Hibernate3.jar:hibernate Core API implementation

Javassist-3.12.0.GA.jar: a dynamic Java code generation tool

Jta-1.1.jar: standard Java transaction interface

Slf4j-api-1.6.1.jar: log management API

Slf4j-nop-1.6.1.jar: log management.

1. Persistence classes are as follows:

Customer.java

Package com.yaxing.entity; import java.util.HashSet; import java.util.Set; / * customer class * * / public class Customer {private Long id; private String name; private Set orders = new HashSet (); public Long getId () {return id;} public void setId (Long id) {this.id = id } public String getName () {return name;} public void setName (String name) {this.name = name;} public Set getOrders () {return orders;} public void setOrders (Set orders) {this.orders = orders;}}

Order.java

Package com.yaxing.entity; / * * order class * * / public class Order {private Long id; private Customer customer; private String orderNumber; public Long getId () {return id;} public void setId (Long id) {this.id = id } public Customer getCustomer () {return customer;} public void setCustomer (Customer customer) {this.customer = customer;} public String getOrderNumber () {return orderNumber;} public void setOrderNumber (String orderNumber) {this.orderNumber = orderNumber;}}

The explanation is as follows: this is a typical one-to-many relationship. That is, a customer will have multiple orders, and an order must belong to a customer, so for an order, if the customer does not exist, the order is meaningless. What is set here is a two-way association. Because there may be a large number of such requirements in the business:

Query all customer orders

Query the customer to which the order belongs according to the given order

Establishing an association between a class and a class makes it easy to navigate from one object to another, as follows:

/ * * order class * * / public class Order {private Long id; private Customer customer; / /...}

This navigates from the order object to the customer object, and the navigation from the order object to the customer object is as follows: given the order object, get the costomer object associated with it.

Customer customer = order.getCustomer ()

So for a given costomer object, how do you navigate from the customer object to the order object? Because the customer object contains a set of order, that is, a customer will have multiple orders.

So for a given customer, to query all orders, the code is as follows:

A Set collection is returned.

Customer.getOrders (); / / returns a collection of set, accessed with an iterator.

The operation of the collection class is not the content of this article, readers can refer to other articles. If you don't know, you can leave a message at the end of this article.

II. Databases and configuration files

The established database is shown in figure 2:

Figure 2

Note that Id is a self-increasing numeric type. Here the Orders table name problem: because order is a keyword, as a table name, will report an error, Sql Server keyword as the table name field name processing is: when using the bracket [], sometimes the development did not notice this, the judgment error is also troublesome, about this, see another blog article: Hibernate error caused by using keywords as table name.

The configuration file is as follows: Customer.hbm.xml

The explanation is as follows:

The ① element specifies the mapping between the class and the table, and if the table attribute is not specified, hibernate uses the class name as the table name. One includes a child element and multiple child elements.

The ② element sets the mapping between the OID (Object Identifier) of the persistence class and the primary key of the table, and the above configuration code indicates that the id property of the Customer class corresponds to the Id field of the Customer table.

The child elements of the ③ element are used to specify the object identifier generator, which is responsible for generating unique identifiers for the OID. An introduction to common object identifier generators will be introduced later. In this article, native is used to indicate that hibernate is selected based on the underlying database.

The ④ child element sets the mapping between the properties of the class and the fields of the table. Common attributes include

Name: specifies the name of the property of the persistent class

Type: specifies the hibernate mapping type, which is a bridge between the java type and the Sql type. For example, the type corresponding to java.lang.String is string. For details, please refer to the corresponding relationship among the three. If no mapping type is set for an attribute, hibernate uses java's radiation mechanism to first identify the java type of the attribute of the persistent class, and then automatically use the corresponding hibernate mapping type.

Column: specifies the field name of the table that maps to the attribute of the persistent class. The above code indicates that the name property of the Customer class corresponds to the Name field of the Customer table.

Not-null: whether it is allowed to be empty. Default is false. Empty exceptions are often encountered in the program, and special attention should be paid to the configuration here!

Element: indicates that the orders attribute of the Customer class is the Set collection, indicating that there is a set of Order objects stored in the orders, indicating that the Orders table in the database references the Customer table through the foreign key CustomerId. Indicates cascading save. Default is none. Values can include all, save-update, delete and delete-orphan. The specific meaning of each parameter is described later.

Order.hbm.xml

Description: the mapping between the customer attribute and the foreign key CustomerId of the Orders table is established. Name is the name of the property of the persistent class. The foreign key CustomerId,class of the table corresponding to the attribute of the persistent class is the type of the attribute of the persistent class. Not-null indicates whether null is allowed. The default value of false.lazy is the retrieval strategy of hibernate, which will be described later.

Third, test code and test results

CustomerAction.java

Package com.yaxing.test; import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.yaxing.entity.Customer; import com.yaxing.util.HibernateUtil; public class CustomerAction {private Customer customer; private List listCustomer; public Customer getCustomer () {return customer } public void setCustomer (Customer customer) {this.customer = customer;} public List getListCustomer () {return listCustomer;} public void setListCustomer (List listCustomer) {this.listCustomer = listCustomer } / * add customer * * / public void addCustomer (Customer customer) {Session s = null; Transaction tx = null; try {s = HibernateUtil.getSession (); tx = s.beginTransaction (); s.save (customer) Tx.commit ();} catch (Exception e) {if (txexamples null) {tx.rollback ();} e.printStackTrace ();} finally {if (slots null) {s.close () } / * Delete customer * * / public void deleteCustomer (Customer customer) {Session s = null; Transaction tx = null; try {s = HibernateUtil.getSession (); tx = s.beginTransaction () S.delete (customer); tx.commit ();} catch (Exception e) {if (txbirthday null) {tx.rollback ();} e.printStackTrace () } finally {if (slots null) {s.close ();} / * * Update customer * * / public void update (Customer customer,String name) {Session s = null; Transaction tx = null Try {s = HibernateUtil.getSession (); tx = s.beginTransaction (); customer.setName (name); s.update (customer); tx.commit ();} catch (Exception e) {if (txroomnull) {tx.rollback () } e.printStackTrace ();} finally {if (slots null) {s.close () } / * query customer * * / public Customer findCustomer (Long id) {Session s = null; Transaction tx = null; try {s = HibernateUtil.getSession (); tx = s.beginTransaction () Customer = (Customer) s.get (Customer.class, id); tx.commit ();} catch (Exception e) {if (txhammer null) {tx.rollback ();} e.printStackTrace () } finally {if (slots null) {s.close ();}} return customer;} / * find all customers * * / public List findAll () {Session s = null Transaction tx = null; try {s = HibernateUtil.getSession (); tx = s.beginTransaction (); Query query = s.createQuery ("from Customer as an order by id asc"); listCustomer = query.list (); for (Iterator iter=listCustomer.iterator (); iter.hasNext ()) ) {Customer customer = (Customer) iter.next (); System.out.println ("customer ID is: + customer.getId () +" customer name is: "+ customer.getName ());} tx.commit () } catch (Exception e) {if (txflowers null) {tx.rollback ();} e.printStackTrace ();} finally {if (slots null) {s.close () }} return listCustomer;}}

The code for OrderAction.java is similar to that for Customer.java.

Package com.yaxing.test; import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import com.yaxing.entity.Order; import com.yaxing.util.HibernateUtil; public class OrderAction {private Order order; private List listorder; public Order getorder () {return order } public void setorder (Order order) {this.order = order;} public List getListorder () {return listorder;} public void setListorder (List listorder) {this.listorder = listorder;} public void addorder (Order order) {Session s = null; Transaction tx = null Try {s = HibernateUtil.getSession (); tx = s.beginTransaction (); s.save (order); tx.commit ();} catch (Exception e) {if (txroomnull) {tx.rollback () } e.printStackTrace ();} finally {if (slots null) {s.close () } / * Delete user * * / public void deleteorder (Order order) {Session s = null; Transaction tx = null; try {s = HibernateUtil.getSession (); tx = s.beginTransaction () S.delete (order); tx.commit ();} catch (Exception e) {if (txbirthday null) {tx.rollback ();} e.printStackTrace () } finally {if (slots null) {s.close ();} public void update (Order order,String number) {Session s = null; Transaction tx = null; try {s = HibernateUtil.getSession () Tx = s.beginTransaction (); order.setOrderNumber (number); s.update (order); tx.commit ();} catch (Exception e) {if (txhammer null) {tx.rollback ();} e.printStackTrace () } finally {if (slots null) {s.close ();} public Order findorder (Long id) {Session s = null; Transaction tx = null; try {s = HibernateUtil.getSession () Tx = s.beginTransaction (); order = (Order) s.get (Order.class, id); tx.commit ();} catch (Exception e) {if (txdestroy null) {tx.rollback ();} e.printStackTrace () } finally {if (slots null) {s.close ();}} return order;} public List findAll () {Session s = null; Transaction tx = null; try {s = HibernateUtil.getSession () Tx = s.beginTransaction (); Query query = s.createQuery ("from Order as an order by id asc"); listorder = query.list (); for (Iterator iter=listorder.iterator (); iter.hasNext ();) {Order order = (Order) iter.next () System.out.println ("order ID is:" + order.getId () + "order number is:" + order.getOrderNumber ());} tx.commit ();} catch (Exception e) {if (txorders null) {tx.rollback () } e.printStackTrace ();} finally {if (slots null) {s.close ();}} return listorder;}}

HibernateUtil.java is as follows:

Package com.yaxing.hibernate.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public final class HibernateUtil {private static SessionFactory sessionFactory; private HibernateUtil () {} static {Configuration cfg = new Configuration (); cfg.configure (); sessionFactory=cfg.buildSessionFactory () } public static SessionFactory getSessionFactory () {return sessionFactory;} public static Session getSession () {return sessionFactory.openSession ();}}

The test code is as follows:

Package com.yaxing.test; import com.yaxing.entity.Customer; public class Test {public static void main (String args []) {Customer customer = new Customer (); customer.setName ("51CTO"); CustomerAction ca = new CustomerAction (); / * * add object * / ca.addCustomer (customer);}

Once allowed, the printed SQL statement is as follows:

Hibernate: insert into Customer (Name) values (?)

Next, let's go to the database to see if the record has been inserted:

Figure 3

As you can see, as shown in figure 3, the record was inserted successfully!

Next, let's take a look at all the queries:

/ * query all * * / ca.findAll ()

Output:

Hibernate: select customer0_.Id as Id1_ Customer0_.Name as Name1_ from Customer customer0_ order by customer0_.Id asc customer ID is: 2 customer name is: null customer ID is: 4 customer name is: 51CTO customer ID is: 5 customer name is: 51CTO customer ID is: 6 customer name is: 51CTO customer ID is: 7 customer name is: 51CTO customer ID is: 8 customer name is: 51CTO

Next, we delete the record with an ID of 8 that we just tested

/ * Delete specified object * / Customer customer = ca.findCustomer (8L); ca.deleteCustomer (customer)

The SQL statement you run is as follows:

Hibernate: select customer0_.Id as Id1_0_, customer0_.Name as Name1_0_ from Customer customer0_ where customer0_.Id=? Hibernate: select orders0_.CustomerId as CustomerId1_1_, orders0_.Id as Id1_, orders0_.Id as Id0_0_, orders0_.OrderNumber as OrderNum2_0_0_, orders0_.CustomerId as CustomerId0_0_ from Orders orders0_ where orders0_.CustomerId=? Hibernate: delete from Customer where Id=?

You can check that the record with an Id of 8 has been deleted!

Finally, a cascaded save:

/ * * Save order * cascade save * / Customer customer = new Customer (); customer.setName ("google"); ca.addCustomer (customer); Order order = new Order (); order.setOrderNumber ("5 cases"); order.setCustomer (customer) Oa.addorder (order)

The SQL statement executed is as follows:

Hibernate: insert into Customer (Name) values (?) Hibernate: insert into Orders (OrderNumber, CustomerId) values Hibernate: update Customer set Name=? Where Id=?

You can view the following records:

Finally, post the configuration code of hibernate:

Org.hibernate.dialect.SQLServerDialect jdbc:jtds:sqlserver://server:1434/hibernateTest sa 711 and above net.sourceforge.jtds.jdbc.Driver true true jtds It is an example analysis of Hibernate3.6 application. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report