1. Steps for using hibernate in Java applications
- Create a configuration file for hibernate
- Create persistence class
- Create object-link ing File
- Write database access code through hibernate API
2. Structure of the helloapp Application
Iii. Hibernate configuration file (hibernate. properties)
hibernate.dialect=org.hibernate.dialect.MySQLDialecthibernate.connection.driver_class=com.mysql.jdbc.Driverhibernate.connection.url=jdbc:mysql://localhost:3306/SAMPLEDBhibernate.connection.username=roothibernate.connection.password=1234hibernate.show_sql=true
4. Create a persistent Customer
- The persistence class complies with the JavaBean specification and contains some attributes, as well as the corresponding getXXX () and setXXX () methods.
- The persistence class has an id attribute that uniquely identifies each object of the Customer class. In object-oriented terminology, this id attribute is called an Object Identifier (OID, Object Identifier), which is usually represented by integers.
- Hibernate requires that the persistence class provide a default constructor without parameters.
package mypack;import java.io.Serializable;import java.sql.Date;import java.sql.Timestamp;public class Customer implements Serializable { private Long id; private String name; private String email; private String password; private int phone; private String address; private char sex; private boolean married; private String description; private byte[] image; private Date birthday; private Timestamp registeredTime; public Customer(){} public Long getId(){ return id; } private void setId(Long id){ this.id = id; } public String getName(){ return name; } public void setName(String name){ this.name=name; } public String getEmail(){ return email; } public void setEmail(String email){ this.email =email ; } public String getPassword(){ return password; } public void setPassword(String password){ this.password =password ; } public int getPhone(){ return phone; } public void setPhone(int phone){ this.phone =phone ; } public String getAddress(){ return address; } public void setAddress(String address){ this.address =address ; } public char getSex(){ return sex; } public void setSex(char sex){ this.sex =sex ; } public boolean isMarried(){ return married; } public void setMarried(boolean married){ this.married =married ; } public String getDescription(){ return description; } public void setDescription(String description){ this.description =description ; } public byte[] getImage() { return this.image; } public void setImage(byte[] image) { this.image = image; } public Date getBirthday() { return this.birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Timestamp getRegisteredTime() { return this.registeredTime; } public void setRegisteredTime(Timestamp registeredTime) { this.registeredTime = registeredTime; }}
Note:
- The getXXX () and setXXX () methods can use any access level. Their Naming rules must comply with specific naming rules. "get" and "set" follow the attribute name, the first letter of the attribute name is in upper case. For example, the get method of the name attribute is getName ().
- If the attribute of the persistence class is boolean, its get method name can be prefixed with get or is.
5. Create a database Schema
drop database if exists SAMPLEDB;create database SAMPLEDB;use SAMPLEDB;create table CUSTOMERS ( ID bigint not null primary key, NAME varchar(15) not null, EMAIL varchar(128) not null, PASSWORD varchar(8) not null, PHONE int , ADDRESS varchar(255), SEX char(1) , IS_MARRIED bit, DESCRIPTION text, IMAGE blob, BIRTHDAY date, REGISTERED_TIME timestamp);
6. Create an object-link ing file Customer. hbm. xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<Generator> A child element is used to set the identifier generator. Hibernate provides multiple built-in implementations.
- <Property> element ing Value Type property
Name attribute: Specifies the name of the attribute of the persistence class. Column attribute: Specifies the field name of the table mapped to the attribute of the class. Type attribute: Specifies the Hibernate ing type. The Hibernate ing type bridges the Java and SQL types.
Advantages of using XML files to configure object-link ing:
- Hibernate does not penetrate into the upper-layer domain model or the lower-layer data model.
- Software developers can independently design domain models without forcing them to comply with any specification.
- Database designers can design data models independently without forcing them to comply with any specification.
- Object-link ing does not depend on any program code. To Modify Object-link ing, you only need to modify the XML file without modifying any program, which improves the flexibility of the software, and makes maintenance more convenient.
VII,Create a BusinessService class
Package mypack; import javax. servlet. *; import org. hibernate. *; import org. hibernate. cfg. configuration; import java. io. *; import java. SQL. date; import java. SQL. timestamp; import java. util. *; public class BusinessService {public static SessionFactory sessionFactory;/** initialize Hibernate and create SessionFactory instance */static {try {// The configuration information of the Hibernate configuration file based on the default location, create a Configuration instance Configuration config = new Configuration (); // Load the object-link ing file config of the Customer class. addClass (Customer. class); // create a SessionFactory instance */sessionFactory = config. buildSessionFactory ();} catch (RuntimeException e) {e. printStackTrace (); throw e ;}/ ** query all Customer objects, and then call the printCustomer () method to print the Customer object information */public void findallmers MERs (ServletContext context, PrintWriter out) throws Exception {Session session = sessionFactory. openSession (); // create a session Transac Tion tx = null; try {tx = session. beginTransaction (); // start a transaction Query query = session. createQuery ("from Customer as c order by c. name asc "); List customers = query. list (); for (Iterator it = customers. iterator (); it. hasNext ();) {printCustomer (context, out, (Customer) it. next ();} tx. commit (); // commit transaction} catch (RuntimeException e) {if (tx! = Null) {tx. rollback ();} throw e;} finally {session. close () ;}/ ** persists a Customer object */public void saveCustomer (Customer customer) {Session session = sessionFactory. openSession (); Transaction tx = null; try {tx = session. beginTransaction (); session. save (customer); tx. commit ();} catch (RuntimeException e) {if (tx! = Null) {tx. rollback ();} throw e;} finally {session. close () ;}}/** load a Customer object according to the OID, and modify its properties */public void loadAndUpdateCustomer (Long customer_id, String address) {Session session = sessionFactory. openSession (); Transaction tx = null; try {tx = session. beginTransaction (); Customer c = (Customer) session. get (Customer. class, customer_id); c. setAddress (address); tx. commit ();} catch (RuntimeExcep Tion e) {if (tx! = Null) {tx. rollback ();} throw e;} finally {session. close () ;}/ ** delete Customer object */public void deleteCustomer (Customer customer) {Session session = sessionFactory. openSession (); Transaction tx = null; try {tx = session. beginTransaction (); session. delete (customer); tx. commit ();} catch (RuntimeException e) {if (tx! = Null) {tx. rollback ();} throw e;} finally {session. close () ;}}/** select to output the Customer object information to the console or Web page */private void printCustomer (ServletContext context, PrintWriter out, Customer customer) throws Exception {if (context! = Null) printCustomerInWeb (context, out, customer); else printCustomer (out, customer);}/** outputs the information of the Customer object to the console, for example, DOS console */private void printCustomer (PrintWriter out, Customer customer) throws Exception {byte [] buffer = customer. getImage (); FileOutputStream fout = new FileOutputStream ("photo_copy.gif"); fout. write (buffer); fout. close (); out. println ("------ the following is" + customer. getName () + "Personal Information ------"); out. printl N ("ID:" + customer. getId (); out. println ("Password:" + customer. getPassword (); out. println ("E-Mail:" + customer. getEmail (); out. println ("Tel:" + customer. getPhone (); out. println ("Address:" + customer. getAddress (); String sex = customer. getSex () = 'M '? "Male": "female"; out. println ("Gender:" + sex); String marriedStatus = customer. isMarried ()? "Married": "Unmarried"; out. println ("Marital status:" + marriedStatus); out. println ("birthday:" + customer. getBirthday (); out. println ("registration time:" + customer. getRegisteredTime (); out. println ("self-introduction:" + customer. getDescription ();}/** output the information of the Customer object to the dynamic webpage */private void printCustomerInWeb (ServletContext context, PrintWriter out, Customer customer Customer) throws Exception {// Save the photo byte [] buffer = customer. getImage (); String path = context. getReal Path ("/"); FileOutputStream fout = new FileOutputStream (path + "photo_copy.gif"); fout. write (buffer); fout. close (); out. println ("------ the following is" + customer. getName () + "Personal Information ------" + "<br>"); out. println ("ID:" + customer. getId () + "<br>"); out. println ("Password:" + customer. getPassword () + "<br>"); out. println ("E-Mail:" + customer. getEmail () + "<br>"); out. println ("Tel:" + customer. getPhone () + "<br>"); out. println ("Address:" + custome R. getAddress () + "<br>"); String sex = customer. getSex () = 'M '? "Male": "female"; out. println ("Gender:" + sex + "<br>"); String marriedStatus = customer. isMarried ()? "Married": "Unmarried"; out. println ("Marital status:" + marriedStatus + "<br>"); out. println ("birthday:" + customer. getBirthday () + "<br>"); out. println ("registration time:" + customer. getRegisteredTime () + "<br>"); out. println ("self-introduction:" + customer. getDescription () + "<br>"); out. println (" <p>");} public void test (ServletContext context, PrintWriter out) throws Exception {Customer customer Customer = new Customer (); customer. setName ("Tom"); customer. setEmail ("tom@yahoo.com"); customer. setPassword ("1234"); customer. setPhone (55556666); customer. setAddress ("Shanghai"); customer. setSex ('M'); customer. setDescription ("I am very honest. "); // set the imageid of the customerobject, which is a number of nodes. The binary data in the photo.gif file is saved. // The photo.gif file and BusinessService. the class file is located in the same directory InputStream in = this. getClass (). getResourceAsStream ("photo.gif"); byte [] buffer = new byte [in. available ()]; in. read (buffer); customer. setImage (buffer); // set the birthday attribute of the Customer object, which is java. SQL. date type customer. setBirthday (Date. valueOf ("1980-05-06"); saveCustomer (customer); findAllCustomers (context, out); loadAndUpdateCustomer (customer. getId (), "Beijing"); findAllCustomers (context, out); deleteCustomer (customer);} public static void main (String args []) throws Exception {new BusinessService (). test (null, new PrintWriter (System. out, true); sessionFactory. close ();}}
This method calls the save () method of the Session and persists the Customer object to the database.
tx = session.beginTransaction(); session.save(customer); tx.commit();
When you run session. save (), Hibernate executes the following SQL statement:
insert into CUSTOMERS (ID, NAME, EMAIL, PASSWORD, PHONE, ADDRESS, SEX, IS_MARRIED,DESCRIPTION, IMAGE, BIRTHDAY, REGISTERED_TIME) values(1,'Tom','tom@yahoo.com','1234',55556666,'Shanghai','M',0,'I am very honest.', ,'1980-05-06',null)
The id attribute of the Customer object is not set in the test () method. Hibernate uses the increment identifier generator to automatically assign values to the OID in ascending mode based on the configuration of the ing file. The ing code in the Customer. hbm. xml file is as follows:
<id name="id" column="ID" type="long"> <generator class="increment"/> </id>
- FindAllCustomers () method
This method queries all Customer objects through the Query interface.
Tx = session. beginTransaction (); // start a transaction Query query = session. createQuery ("from Customer as c order by c. name asc "); List customers = query. list (); for (Iterator it = customers. iterator (); it. hasNext ();) {printCustomer (context, out, (Customer) it. next ();} tx. commit (); // submit the transaction
The parameter "from customer as C order by C. Name ASC" of the createquery () method of the session uses the Hibernate query language. When you run the query. List () method, Hibernate executes the following SQL statement:
select * from CUSTOMERS order by NAME asc;
- LoadAndUpdateCustomer () method
This method calls the get () method of the Session, loads the Customer object, and then modifies the attributes of the Customer object.
Tx = session. begintransaction (); customer C = (customer) session. get (customer. class, customer_id); C. setaddress (Address); // modify the address attribute TX of the customer object in memory. commit ();
The above code first calls the get () method of the Session, which retrieves matching Customer objects from the database based on the OID specified by the parameter. Hibernate will execute the following SQL statement:
select * from CUSTOMERS where ID=1;
The loadandupdatecustomer () method then modifies the address attribute of the customer object. So Will hibernate synchronously update the corresponding MERs table records in the database? The answer is yes. Hibernate uses the dirty check mechanism to synchronously update data in the database according to the state changes of the customer object in the memory. hibernate will execute the following SQL statement:
update CUSTOMERS set NAME="Tom",EMAIL="Tom@yahoo.com"…ADDRESS="Beijing"… where ID=1;
Although only the address attribute of the customer object has changed, the update statement executed by hibernate contains all fields.
This method calls the delete () method of the Session to delete a specific Customer object:
tx = session.beginTransaction(); session.delete(customer); tx.commit();
When the session. Delete () method is run, Hibernate executes the following SQL Delete statement based on the oId of the customer object:
delete from CUSTOMERS where ID=1;
8,