Simple Application of Hibernate

Source: Internet
Author: User
Tags ibm developerworks

1. Overview of hibernate development steps
I just briefly summarized the development steps of hibernate. It may be one-sided, but I hope you will share it with me.
The development process of hibernate can be summarized into four steps:

  • Configure Hibernate and write out the configuration file corresponding to the hibernate configuration file and database operations.
  • Determine the data table and create a Persistent Object
  • Write the ing description of objects and Data Tables
  • Writing and business logic

 

Ii. Examples

The following is an example based on the above steps. Here is just a simple application. All code can be run after testing.
My testing environment: tomcat5.0 + MySql

The overall structure of the instance:

  1. Java file structure:
    • Course. Java creates the corresponding Persistent Object Based on the table in the database
    • Hibernatebase. Java encapsulates common hibernate operations
    • Coursebean. Java writes business logic classes based on the needs of persistent objects. It inherits the hibernatebase class
  2. Configuration Information Structure
    • Hibernate. cfg. xml this is the configuration file of hibernate.
    • The configuration file of the course. HBM. xml Persistent object. It is the ing file between the object and the data table.
  3. JSP file structure
    • On the course. jsp homepage, you can add data.
    • Fuzzy query operations provided by querycourse. jsp
    • Viewall. jsp display all data
    • Deletecourse. jsp Delete the specified record

Next, follow the development steps I mentioned to create a simple demo.

Instance:

  1. Configure hibernate (once)
    In Web applications, the best configuration file is hibernate. cfg. XML file, because it can easily add a Persistent Object ing description file, that is, class name + "HBM. XML ", not like hibernate. properties must be added to the initialization code.
    Hibernate. cfg. xml file, usually put in the application server's current application of the WEB-INF/classess directory.
    Example:
    Hibench. cfg. xml
    <! Doctype hibernate-Configuration
    Public "-// hibernate/hibernate configuration DTD // en"
    Http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd>

    <Hibernate-configuration>
    <Session-factory>
    <Property name = "connection. datasource"> JAVA: COMP/ENV/jdbc/hibernate </property>
    <Property name = "show_ SQL"> false </property>
    <Property name = "dialect"> net. SF. hibernate. dialect. mysqldialect </property>

    <! -- Mapping Files -->
    <Mapping Resource = "course. HBM. xml"/>
    </Session-factory>

    </Hibernate-configuration>

    A data source is configured here. The JNDI name of the data source is JDBC/hibernate, and the SQL dialect is MySQL. The JDBC/hibernate data source needs to be configured in APP server, and the factory attribute must be added. The value is org. Apache. commons. DBCP. basicdatasourcefactory.

  2. Determine the data table and create a Persistent Object
    Hibernate is used to encapsulate a simple data table. The table name is courses. It has two fields: ID, primary key of the courses table, and name, indicates the name of courses.
    Create a courses table in the database:
     
    Create Table courses (courseid varchar (32) not null, name varchar (32), constraint pk_courses primary key (courseid ))
     
    Write persistent objects for the courses table, 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; }}

    It can be seen that the course class also contains two attributes: ID and name. Their attributes correspond one to one with the fields in the courses table, and their types are consistent.

  3. Write the ing description of objects and data tables, that is, the O-R ing file.
    Create a course. HBM. XML description file under the hibernate/WEB-INF/classes directory
    Course. HBM. xml
    <? XML version = "1.0"?>
    <! Doctype hibernate-mapping public
    "-// Hibernate/hibernate mapping DTD 2.0 // en"
    Http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd>

    <Hibernate-mapping>
    <Class name = "com. hellking. Study. hibernate. Course" table = "courses" dynamic-update = "false">
    <ID name = "ID" column = "courseid" type = "string" unsaved-value = "any">
    <Generator class = "assigned"/>
    </ID>
    <Property name = "name" type = "string" update = "true" insert = "true" column = "name"/>
    </Class>
    </Hibernate-mapping>

    In this description file, the course class corresponds to the courses table in the database. Each attribute in the Set class corresponds to each field in the table one by one, and each field has different attributes, they can set different attributes for different needs. (For the specific meanings of each descriptor, see the Chinese Reference Documents of hibernate)
    In addition, you must specify the Persistent Object ing relationship in hibernate. cfg. xml.

    ••••••
    <! -- Mapping Files -->
    <Mapping Resource = "course. HBM. xml"/>
    ••••••
  4. Writing and business logic
    We have encapsulated a table named courses and the configuration is complete. The next task is to use them in Web application development. To demonstrate different types of database operations in hibernate, the Web application we developed has the following features:
    • Add a course
    • Delete A Course
    • Fuzzy search by course name
    • View All course in the system

    Since there are some common operations for access through hibernate, here we encapsulate these common operations in a specialized class, in this way, other classes can inherit from the classes that write common operations and encapsulate hibernate operations, that is, 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; // session factory, used to create a session protected session; // hibernate session protected transaction; // hibernate Transaction Private Final Static logger = logger. getlogger (hibernatebase. class); Public hibernatebase () {This. inithibernate () ;}// help method protected void inithibernate () {// load the configuration and construct the 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 begintransaction () {try {session = sessionfactory. opensession (); transaction = session. begintransaction ();} catch (hibernateexception he) {he. printstacktrace (); logger. error (HE. getmessage () ;}}/*** ends a hibernate transaction */protected void endtransaction (Boolean commit) {try {If (COMMIT) transaction. commit (); else // if it is a read-only operation, the transaction does not need to be commit. rollback ();} catch (hibernateexception he) {he. printstacktrace (); logger. error (HE. getmessage ());}}}

    The business logic class coursebean is written below, 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. getlogger (coursebean. class); Public coursebean () {super () ;}/ *** added a course */Public void addcourse (course St) {try {begintransaction (); Session. save (ST); endtransaction (true);} catch (hibernat Eexception he) {he. printstacktrace (); log. error (HE. getmessage () ;}}/*** query system all course. The returned iterator contains the course Persistent Object. */Public iterator getallcourses () {iterator it = NULL; try {string querystring = "select courses from course as courses"; begintransaction (); query = session. createquery (querystring); It = query. iterate ();} catch (hibernateexception he) {he. printstacktrace (); log. error (HE. getmessage ();} return it;}/*** Delete the course */Public void deletecourse (string ID) for the given ID {try {begintransaction (); course = (Course) session. load (course. class, ID); Session. delete (course); endtransaction (true);} catch (hibernateexception he) {he. printstacktrace (); log. error (HE. getmessage () ;}}/*** perform fuzzy search based on the Course name. The returned iterator contains the 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 = session. createquery (querystring); query. setstring ("name", "%" + name + "%"); It = query. iterate ();} catch (hibernateexception he) {he. printstacktrace (); log. error (HE. getmessage () ;}return it ;}}

    In coursebean, Hibernate is used to operate potential database resources.
    Note: In the query statement select C from course as c Where C. in name like: name, it is similar to a common SQL statement, but it is different. in the database, the name of the table used is courses, in this query statement, course is used, which is the same as the name of the Persistent Object. That is to say, the query concept is to query persistent objects rather than database records. After a query object is created, you need to set the query parameters. This method is similar to setting parameters in the preparedstatement object in JDBC. Run the "iterator it = query. iterate ()" Statement and return an iterator object. Here we use the query mechanism provided by hibernate. Generally, the JDBC query returns the resultset object, and here the iterator that contains the coursebean object.
    In the delete operation method, start a transaction first, and then pass the session. load (course. class, ID) method to load the persistence object of the specified ID, and then through the session. delete (course) "to delete the loaded course and end the hibernate transaction.

  5. Call business logic in JSP
    Write web pages, through hibernate O-R ing, operate on persistent objects. Because these operations call methods in the coursebean class, the code for each page is not provided here, just a brief description.
    • Add data on the course. jsp page. The addcourse (course St) method of the coursebean class is called.
    • Fuzzy query is completed on the querycourse. jsp page. The getsomecourse (string name) method of the coursebean class is called.
    • Query all data on the viewall. jsp page. The getallcourses () method of the coursebean class is called.
    • Delete the specified data on the deletecourse. jsp page. Call the deletecourse (string ID) method of the coursebean class.

To sum up, the above is just the result that I learned from an article about hibernate on IBM developerworks after I started hibernate. For more information, see the original article. This is also a basic entry point, even if it is for everyone, haha! Other aspects of hibernate, such as parent-child relationships and transactions, have not been studied in depth, and we hope to make up for them in future studies. Please give me more advice. Thank you.

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.