Hibernate's simple application

xiaoxiao2021-03-05  26

Hibernate's simple application

1. Overview Hibernate's development steps about Hibernate's development steps, I just conclude, maybe more than one, but I hope everyone will share. The development process of Hibernate can be summarized as four steps:

Configure Hibernate to write the corresponding configuration files about Hibernate configuration files and database operations. Determine the data sheet, create a persistent object write object and data sheet mapping description writing and business logic

Second, an example

Because the above steps are performed, it is just a simple application. All code can be run through the test. My test environment: Tomcat5.0 mysql

The overall structure of this example:

1. Java class file structure:

o Course.java Create a corresponding lasting object according to the table in the database

o HibernateBase.java Package Hibernate's common operation

o CourseBean.java writes business logic classes based on persistent objects, which inherits hibernateBase classes

2. Configure the information structure

o hibernate.cfg.xml This is the configuration file of Hibernate

o course.hbm.xml lasting object configuration file, it is an object and data sheet mapping file

3. JSP file structure

o Course.jsp Main page, add data

O QueryCourse.jsp provides a fuzzy query operation

o Viewall.jsp Display all data

o DeleteCourse.jsp Deletes the specified record

Below, make a simple Demo according to the development steps I said.

Example:

1. Configuring Hibernate (once) General Hibernate's configuration files is preferably hibernate.cfg.xml file because it can easily increase the mapping description file of lasting objects, ie class name hbm.xml Do not have to be added to the initialization code like hibernate.properties. Hibernate.cfg.xml files, generally placed in the web-inf / class directory of the application server. example:

hiernate.cfg.xml java: comp / env / jdbc / hibernate false net .sf.hibernate.dialev.MysqldiaAlact 2. Configuration A data source, the JNDI name of the data source is JDBC / Hibernate, and the SQL dialect is mysql. In App Server, you need to configure data source JDBC / Hibernate, and you need to add the factory properties, the value is org.apache.commons.dbcp.basicDataSourceFactory

3. Determine the data sheet, create a persistent object to encapsulate a simple data sheet, this table is Courses, it has two fields, one is ID, it is the primary key of the course table; the other is Name, indicating course name. Create a CourseS table in the database: Create Table Courses (Courseid Varchar (32) Not Null, Name Varchar (32), Constraint PK_Courss Primary Key (CourseId) Writing a persistent object for Courses tables, class Course

Course.java package com.hellking.study.hibernate; public class Course {private String id; private String name; public void setId (String string) {id = string;} public String getId () {return id;} public void setName (String name) {this.name = name;} public string getname () {return this.name;}}

4. It can be seen that two properties, ID, and names, IDs, and table Courses are part, and the type is consistent.

5. Write the mapping description of objects and data sheets, that is, the O-R mapping files create new course.hbm.xml description files in Hibernate / Web-INF / CLASSES directory

Course.hbm.xml 6. Declare that class course corresponds to table Courses in the database, setting each attribute in the class and each field in the table Correspondingly, each field of which is equipped with different properties, which can set different properties for different needs. (For details, please refer to the Hibernate Chinese Reference Document) At the same time, you need to specify this persistent object mapping relationship in hibernate.cfg.xml.

•••••••! •••••

7. Writing and Business Logic We have already packaged a table named coursees and configured. The next task is to use them in web application development. To demonstrate different types of operations in the database in Hibernate, our development Web application has the following features:

o Add a Course

o Delete a Course

o Follow the name of Course

o View all Course in the system

Since there is some common operation by using Hibernate, we will package these commonly operated operations in a specialized class, so that other classes can inherit it // to write the common operation class, encapsulate Hibernate's operation, the HibernateBase class

HibernateBase.java package com.hellking.study.hibernate; import net.sf.hibernate *;. Import net.sf.hibernate.cfg *;. Import org.apache.log4j *;. Public class HibernateBase {protected static SessionFactory sessionFactory; // session factory, used to create sessions protected session session; // hibernate session protected transaction transaction; // hibernate transaction private final static Logger logger = Logger.getLogger (HibernateBase.class); public HibernateBase () {this.initHibernate () ;} // helper method protected void initHibernate () {// load configuration, configured SessionFactory object try {configuration conf = new configuration (); sessionFactory = new configuration () configure () buildSessionFactory ();..} catch (HibernateException he ) {HE.PrintStackTrace (); logger.error (he.getMessage ());}} / ** * Start a hibernate transaction * / protected void based begintractions () {Try {session = sessionFactory.openSession (); transaction = session .begintransact ION ();} catch (he.printstacktrace (); logger.error (HE.GetMessage ());}} / ** * End a hibernate transaction * / protected void endtransaction (boolean commit) {try { If (commit) transaction.commit (); Else // If it is read-only, do not need Commit transaction.rollback ();} catch (hibernateException he) {he.printstacktrace (); logger.error (he. GetMessage ());}}} The following is written under the business logic class, which inherits the HibernateBase class.

CourseBean.java package com.hellking.study.hibernate; import net.sf.hibernate *;. Import org.apache.log4j.Logger; import java.util.Iterator; public class CourseBean extends HibernateBase {private final static Logger log = Logger PUBLIC CourseBean () {super ();} / ** * Add a course * / public void addcourse (course st) {begintransaction (); session.save (st); endtransaction True);} catch (HibernateException He); log.error (he.getMessage ());}} / ** * Query all Course in the system, returning to Iterator containing Course lastu . * / Public Iterator getAllCourses () {Iterator it = null; try {String queryString = "select courses from Course as courses"; beginTransaction (); Query query = session.createQuery (queryString); it = query.iterate ();} Catch (HibernateException He); log.error (HE.GetMessage ());} Return It;} / ** * Coursecourse (String ID) {Try {Try {Try {TRING ID BeGintransAction (); course course = (course) session.load (course.class, id); session.delete (course);} catch (hibernateException he) {he.printstacktrace (); log.error HE.GetMessage ());}} / ** * Press COURSE's name to make a fuzzy lookup, returning to Iterator with a COURSE persistent object.

* / Public Iterator getSomeCourse (String name) {Iterator it = null; try {String queryString = "select c from Course as c where c.name like: name"; beginTransaction (); Query query = session.createQuery (queryString); Query.setString ("Name", "%" Name "%"); it = query.iterate ();} catch (HibernateException He) {HE.PrintStackTrace (); log.error (HE.GetMessage ()); } Return It;}} In CourseBean, operate potential database resource through Hibernate Note: In Query Statement Select C from Course As C Where C.Name Like: Name, it is similar to the normal SQL statement, but different, In the database, the name of the table used is coursees, and in this query statement is COURSE, it is consistent with the name of lasting objects, that is, this query is to query the persistent object, not the database record. After you create query object Query, you need to set the query parameters, which will similar ways to the parameters in the PreparedStatement object in the JDBC. Returns an Iterator object by "Iterator IT = Query.Iterate () statement. Here, the Query mechanism provided here, the general JDBC query returns the ResultSet object, and the return here is the Iterator containing the CourseBean object. In the method of deleting the operation, first start a transaction, then load the lasting object of the specified ID through the session.Load (Course.class, ID) method, then remove the loaded Course by "session.delete (course) And end Hibernate transactions.

8. Call the business logic in the JSP to write the WEB page, and operate the persistent object via Hibernate's O-R mapping. Since these operations are ways to call the CourseBean class, this is not given the code of each page, just a simple explanation.

o Add data to complete it through the course.jsp page. Calling is an AddCourse (Course St) method for Coursebean classes

o Fuzzy query, complete through the querycourse.jsp page. Calling is a GetSomeCourse (String Name) method for Coursebean classes.

o Query all data and completes through the viewall.jsp page. Calling a GetAllCourses () method for the CourseBean class

o Delete the specified data and completes it through the deletecourse.jsp page. Calling is a deletecourse (String ID) method for the CourseBean class.

This article comes from the network - everyone discusses

转载请注明原文地址:https://www.9cbs.com/read-35126.html

New Post(0)