ORM ---- hibernate getting started Demo (invincible detailed version ),

Source: Internet
Author: User

ORM ---- hibernate getting started Demo (invincible detailed version ),

1. Introduction to Hibernate (open source object link ing framework:

Hibernate is an open-source object relationship ing framework that encapsulates JDBC very lightweight objects. It establishes ing between POJO and database tables and is a fully automated orm framework, hibernate can automatically generate and execute SQL statements, so that Java programmers can use the object programming thinking to manipulate the database as they wish. Hibernate can be used in any situation where JDBC is used. It can be used in Java client programs or Servlet/JSP Web applications. The most revolutionary is that, hibernate can replace CMP in the J2EE architecture of application EJB to fulfill the task of data persistence.

Ii. Features of The Hibernate language 1. Convert database operations into operations on Java objects to simplify development. Modify the record data in the database table by modifying the attributes of a "persistent" object. 2. provides two levels of cache for threads and processes to improve application performance. 3. There are a variety of ing methods to convert the relationships between Java objects to those between database tables. 4. Shielding the differences between different database implementations. In Hibernate, you only need to specify the currently used database in the form of a "dialect", you can generate appropriate SQL statements based on the actual situation of the underlying database. 5. Non-Intrusive: Hibernate does not require the persistence class to implement any interface or inherit any class. POJO is enough. Iii. ORM principles

Iv. hibernate getting started Demo

Jar package used by this project

 

1. I am using a mysql relational database. first create a database and create a customer (customer information) table.

 

2. Create a Customer entity class (persistence class)

A persistence class is a business entity class in an application. Persistence here means that objects of the class can be persistently stored in the database.

Hibernate uses a common JAVA object (POJO), that is, the POJO programming mode for persistence.

This class contains the attributes corresponding to the database table. These attributes are accessed through the getter/setter method, and internal implementation details are hidden from the outside.

Usually, writing persistence classes should follow some rules:

1). The public constructor without parameters must be provided in the persistence class. (If NO constructor is provided, the default constructor is automatically provided. However, if other constructor with parameters is provided

The virtual machine no longer provides the default constructor. You must manually compile the non-parameter constructor ).

2). All attributes in the persistence class are modified using private, and the public setter/getter method is provided.

3). The id attribute OID must be provided, which gradually corresponds to the database table. For example, the following Customer class id attribute

4) Persistence attributes should use the packaging type of the basic data type as much as possible. For example, replace int with Integer and long with Long to be consistent with the default value null of the field in the database table. (For example, if int is partitioned by null and 0, the default value of the int type that is not assigned a value is 0)

5). Do not use final modification for persistence classes. Using final modification will not generate proxy objects for optimization.

Public class Customer {private Integer id; // primary key id private String name; // Customer name private Integer age; // Customer age private String sex; // Customer gender private String city; // customer address/*** @ return the id */public Integer getId () {return id ;} /*** @ param id the id to set */public void setId (Integer id) {this. id = id;}/*** @ return the name */public String getName () {return name ;} /*** @ param name the name to set */public void setName (String name) {this. name = name;}/*** @ return the age */public Integer getAge () {return age ;} /*** @ param age the age to set */public void setAge (Integer age) {this. age = age;}/*** @ return the sex */public String getSex () {return sex ;} /*** @ param sex the sex to set */public void setSex (String sex) {this. sex = sex;}/*** @ return the city */public String getCity () {return city ;} /*** @ param city the city to set */public void setCity (String city) {this. city = city;} // override toString () method @ Overridepublic String toString () {return "Customer [id =" + id + ", name =" + name + ", age = "+ age +", sex = "+ sex +", city = "+ city +"] ";}}

3. Write the Customer ing file Customer. hbm. xml.

The object class Customer does not currently have the ability to perform persistent operations. Hibernate needs to know which table of the Object Class Customer maps to the database Hibernate and which attribute of the class.

Which fields in the database table need to be configured in the ing file.

In the package where the object class Customer is located, create a package named Customer. hbm. the xml ing file defines how the attributes of the Object Class Customer are mapped to the column of the customer table.

Start to write an xml file. You can find the file header information through the following steps:

 

 

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate DTD ing DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

4. Compile the core configuration file hibernate. cfg. xml

The Hibernate ing file reflects the ing information between persistence classes and database tables,

The Hibernate configuration file is mainly used to configure database connections and the values of each attribute required for Hibernate runtime.

Create a file named hibernate. cfg. xml in the src directory of the project.

You can write the xml header as follows:

Compile the hibernate. cfg. xml file

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE hibernate-configuration PUBLIC "-// Hibernate/Hibernate Configuration DTD 3.0 // EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 

5. Write the unit test code as follows:

Public class HibernateTestDemo {// defines the variable Configuration config; SessionFactory sessionFactory; Session session; Transaction transaction; // before indicates that @ Before public void setUp () is executed before the method is executed () {// 1. load hibernate. cfg. xml Configuration config = new Configuration (). configure (); // 2. obtain SessionFactory sessionFactory = config. buildSessionFactory (); // 3. obtain a session = sessionFactory. openSession (); // 4. start transaction = session. beginTransaction () ;}// add operation @ Test public void insert () {// 5. operation Customer customer = new Customer (); customer. setId (1); customer. setName ("zhangsan"); customer. setAge (20); customer. setSex ("man"); customer. setCity ("Guangzhou"); session. save (customer) ;}// delete operation @ Test public void delete () {// first query the Customer customer = (Customer) session. get (Customer. class, 1); // Delete the session. delete (customer);} // query operation @ Test public void select () {Customer customer = (Customer) session. get (Customer. class, 1); System. out. println (customer);} // update operation @ Test public void update () {Customer customer = new Customer (); customer. setId (1); customer. setName ("zhangsan"); customer. setAge (20); customer. setSex ("man"); // modify the address to Beijing customer. setCity ("Beijing"); // update if it exists. If it does not exist, execute the insert operation session. saveOrUpdate (customer);} // After indicates that After the method is executed, @ After public void closeTransaction () {// 6. commit transaction. commit (); // 7. closes the resource session. close (); sessionFactory. close ();}}

1) After the insert operation is executed, open mysql and use select * from customer;. The result is as follows:

2) perform the query operation (view console output)

3. Perform the update operation.

4. delete operation

V. Summary

The super full version of hibernate getting started demo is complete. If you do not understand it or have any questions, please leave a message ~

 

 

 

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.