In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces you in the Java application in the use of Hibernate example analysis, the content is very detailed, interested friends can refer to, hope to be helpful to you.
1. Steps to use Hibernate in Java applications
Create a configuration file for Hibernate
Create a persistence class
Create an object-relational mapping file
Write code to access the database through Hibernate API
II. The structure of Helloapp applications
III. Hibernate configuration file (hibernate.properties)
Hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.connection.url=jdbc:mysql://localhost:3306/SAMPLEDB hibernate.connection.username=root hibernate.connection.password=1234 hibernate.show_sql=true
4. Create a persistent class Customer
The persistence class conforms to the JavaBean specification and contains some properties and corresponding getXXX () and setXXX () methods.
The persistent class has an id property that uniquely identifies each object of the Customer class. In object-oriented terminology, this id attribute is called an object identifier (OID,Object Identifier) and is usually expressed as an integer.
Hibernate requires that a persistent class must provide a default constructor with no parameters.
Package mypack; import java.io.Serializable; import java.sql.Date; import java.sql.Timest 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 take any access level, and their naming rules must conform to a specific naming convention. "get" and "set" are followed by the name of the attribute, and the first letter of the attribute name is uppercase, for example, the get method of the name property is getName ().
If the property of the persistent class is of type boolean, its get method name can be prefixed with either get or is.
5. Create 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 not null, PASSWORD varchar (8) not null, PHONE int, ADDRESS varchar, SEX char (1), IS_MARRIED bit, DESCRIPTION text, IMAGE blob, BIRTHDAY date, REGISTERED_TIME timestamp)
6. Create object-relational mapping file Customer.hbm.xml
Element mapping OID
Child elements are used to set the identifier generator. Hibernate provides several built-in implementations.
Element mapping value type attribute
Name attribute: specifies the name of the property of the persistent class.
Column attribute: specifies the field name of the table that maps to the property of the class.
Type attribute: specifies the Hibernate mapping type. Hibernate mapping type is the bridge between Java type and SQL type.
The advantages of using XML files to configure object-relational mapping:
Hibernate penetrates neither the upper domain model nor the lower data model.
Software developers can design domain models independently without having to force compliance with any specifications.
Database designers can design data models independently without having to force compliance with any specifications.
The object-relational mapping does not depend on any program code. If you need to modify the object-relational mapping, you only need to modify the XML file, but do not need to modify any programs, which improves the flexibility of the software and makes maintenance more convenient.
7. Create 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.Timest import java.util.*; public class BusinessService {public static SessionFactory sessionFactory / * * initialize Hibernate and create SessionFactory instance * / static {try {/ / create a Configuration instance Configuration config = new Configuration () based on the configuration information of the Hibernate configuration file in the default location; / / load the object-relational mapping file config.addClass (Customer.class) of the 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 Customer object information * / public void findAllCustomers (ServletContext context,PrintWriter out) throws Exception {Session session = sessionFactory.openSession (); / / create a session Transaction tx = null Try {tx = session.beginTransaction (); / / start a transaction Query query=session.createQuery ("from Customer asc 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 ();}} / * * persist 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 OID, then 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 (RuntimeException 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 () }} / * * choose to output Customer object information to the console or Web web page * / private void printCustomer (ServletContext context,PrintWriter out,Customer customer) throws Exception {if (contextual null) printCustomerInWeb (context,out,customer); else printCustomer (out,customer) } / * * output the information of the Customer object to the console, such as 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 the personal information of" + customer.getName () + ") Out.println ("ID:" + customer.getId ()); out.println ("password:" + customer.getPassword ()); out.println ("E-Mail:" + customer.getEmail ()); out.println ("phone:" + customer.getPhone ()); out.println ("address:" + customer.getAddress ()); String sex=customer.getSex () = 'customer.getPhone? "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 Customer object to dynamic web page * / private void printCustomerInWeb (ServletContext context,PrintWriter out,Customer customer) throws Exception {/ / Save photo byte [] buffer=customer.getImage (); String path=context.getRealPath ("/"); FileOutputStream fout=new FileOutputStream (path+ "photo_copy.gif"); fout.write (buffer); fout.close () Out.println ("- the following is the personal information of" + customer.getName () + "-" + "
"); out.println (" ID: "+ customer.getId () +"
"); out.println (" password: "+ customer.getPassword () +"
"); out.println (" E-Mail: "+ customer.getEmail () +"
Out.println ("phone:" + customer.getPhone () + "
); out.println ("address:" + customer.getAddress () + "
"); String sex=customer.getSex () = 'sex+?" 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 () + "
); out.println ("
);} public void test (ServletContext context,PrintWriter out) throws Exception {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 image property of the Customer object, which is a byte array that stores the binary data in the photo.gif file / / photo.gif file and the BusinessService.class file 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 property of the Customer object, which is the 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 ();}}
SaveCustomer () method
This method calls the save () method of Session to persist the Customer object to the database.
Tx = session.beginTransaction (); session.save (customer); tx.commit ()
When you run the session.save () method, Hibernate executes the following SQL statement:
Insert into CUSTOMERS (ID, NAME, EMAIL, PASSWORD, PHONE, ADDRESS, SEX, IS_MARRIED,DESCRIPTION, IMAGE, BIRTHDAY, REGISTERED_TIME) values.
The id property of the Customer object is not set in the test () method. According to the configuration of the mapping file, Hibernate uses the increment identifier generator to automatically assign a value to OID incrementally. The relevant mapping code in the Customer.hbm.xml file is as follows:
FindAllCustomers () method
This method queries all Customer objects through the Query interface.
Tx = session.beginTransaction (); / / start a transaction Query query=session.createQuery ("from Customer asc 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 the transaction
The parameter "from Customer asc order by c.name asc" of Session's createQuery () method 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 Session, loads the Customer object, and then modifies the properties of the Customer object.
Tx = session.beginTransaction (); Customer c = (Customer) session.get (Customer.class,customer_id); c.setAddress (address); / / modify the address property tx.commit () of the Customer object in memory
The above code first calls the get () method of Session, which retrieves the matching Customer object from the database according to the OID specified by the parameter, and Hibernate executes the following SQL statement:
Select * from CUSTOMERS where ID=1
The loadAndUpdateCustomer () method then modifies the address property of the Customer object. So, will Hibernate synchronously update the records of the corresponding CUSTOMERS table in the database? The answer is yes. Hibernate uses the dirty checking mechanism to synchronously update the relevant data in the database according to the changes in the state of the Customer object in memory. Hibernate executes the following SQL statement:
Update CUSTOMERS set NAME= "Tom", EMAIL= "Tom@yahoo.com"... ADDRESS= "Beijing"... Where ID=1
Although only the address property of the Customer object has changed, the update statement executed by Hibernate contains all the fields.
DeleteCustomer () method
This method calls the delete () method of Session to delete a specific Customer object:
Tx = session.beginTransaction (); session.delete (customer); tx.commit ()
When you run the session.delete () method, Hibernate executes the following SQL delete statement based on the OID of the Customer object:
Delete from CUSTOMERS where ID=1;
8. Effect picture
This is the end of the sample analysis on the use of Hibernate in Java applications. I hope the above content can be of some help and learn more knowledge. If you think the article is good, you can share it for more people to see.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.