Hibernate official Beginner's tutorial (reprint)

Source: Internet
Author: User

Hibernate official Beginner Tutorial
Part One-the first Hibernate program

First we will create a simple console (console-based) Hibernate program. We use built-in databases (In-memory database) (HSQL DB), so we don't have to install whatever database server.

Let us if we want a small program to be able to save the events we want to focus on and the information about those events. (Translator Note: In the later part of this tutorial, we will use the event directly instead of its Chinese translation "events" to avoid confusion.) )

The first thing we do is build our development folder and put all the Java library files that need to be used. Download the hibernate distribution version number from the download page of the hibernate site. Unpack the package and place all the library files below /lib below the /lib folder below our new development folder. It looks like this:

. +lib  Antlr.jar  cglib-full.jar  asm.jar  asm-attrs.jars  Commons-collections.jar  Commons-logging.jar  ehcache.jar  hibernate3.jar  jta.jar  Dom4j.jar  

This is the minimum set of required libraries (note so we also copied Hibernate3.jar, the main archive) for Hibernate. See the README.txt file in the lib/ directory of the "Hibernate distribution for more information" about R equired and optional Third-party libraries. (Actually, log4j is isn't required but preferred by many developers.) This is the minimum set of library files required for hibernate execution (note that we have also copied the Hibernate3.jar, which is the most important library). The ability to view README.txtunder the lib/ folder for hibernate distribution version numbers to get a lot of other information about required and optional third-party library files (in fact, Log4j is not a required library file but many developers like to use it.

Next we create a class to represent the event that we want to store in the database.

2.2.1. First Class

Our first persistence class is a simple JavaBean class with some simple properties. Let's take a look at the code:

Import Java.util.date;public class Event {    private Long ID;    Private String title;    private date date;    Event () {} public    Long getId () {        return ID;    }    private void SetId (Long id) {        this.id = ID;    }    Public Date getDate () {        return date;    }    public void SetDate (date date) {        this.date = date;    }    Public String GetTitle () {        return title;    }    public void Settitle (String title) {        this.title = title;    }}

You can see that this class accesses the property (getter and setter method) using the standard JavaBean naming convention, which hides the internal field (the field) at the same time (private visibility). This is a recommended design approach, but it is not necessary to do so. Hibernate is also able to access these fields directly, and the advantage of using the accessor method is that it provides the robustness of the program refactoring (robustness).

The ID attribute provides the value of the identity attribute (identifier property) for an event instance-assuming we want to use all of Hibernate's features, then all of our persistent entity classes (persistent Entity Class) (which also contains some secondary dependency classes) requires an identity attribute (identifier property). In fact, most applications, especially Web applications, need to identify specific objects, so you should consider using identity attributes instead of treating them as a limitation. However, we do not normally manipulate the identifier (identifier) of an object directly, so the setter method of the identifier should be declared private (private). This way, when an object is saved, only hibernate can assign an identifier to it. You will find that Hibernate has direct access to the methods (accessor method) and fields (field) that are declared to be at different levels of control, such as public,private and protected. So choosing which way to access the property is entirely up to you, and you can make your choice match your program design.

All persistent classes (persistent classes) require a non-participating constructor (No-argument constructor), since hibernate must use the Java Reflection Mechanism (Reflection) to instantiate the object. The access control of the constructor (constructor) can be private, but when the runtime proxy is generated, it will be required to use at least the package level of interview control, so that no bytecode is programmed (bytecode instrumentation), it is more efficient to get data from a persisted class.

We put this Java source file in our development folder below a folder called src . This folder should look like this now:

. +lib  

In the next step, we will notify Hibernate of this persistent class (Persisten) message

2.2.2. mapping files

Hibernate needs to know how to load (load) and store our persisted class objects. This is where Hibernate mapping files (mapping file) play a role. The mapping file tells hibernate that it should visit which table in the Database (table) and which fields in the table should be used (column).

The basic structure of a mapping file looks like this:

<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping public        "-//hibernate/hibernate mapping DTD 3.0//en"        "http// Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ">

Note that hibernate's DTD is very complex. You can use it in your editor or IDE to proactively prompt and complete (auto-completion) those XML elements (element) and attributes (attribute) that are used for mapping. You can also open dtd-with your text editor. This is the simplest way to navigate through all the elements and parameters, view their default values, and gaze at them to get a general overview. Also note that Hibernate does not get a DTD file from the Web, even though the URL in the XML might suggest it, but hibernate will first look at the classpath of your program. The DTD file is included in the Hibernate3.jarand is also under the src/ path of hibernate distribution.

In a later example, we will shorten the code length by omitting the declaration of the DTD. It is clear, however, that the DTD declaration is necessary in the actual procedure.

In the middle of the two hibernate-mapping tags, we included a class element. All Persistent entity classes (persistent entity classes) (again, including those dependent classes, which are the secondary entities) need a mapping to our SQL database.

All we've done so far is to tell hibernate how to persist and load the Event class object from the database table (table)EVENTS , one row per instance of the corresponding database. Now we will continue to discuss mappings for unique identifier property. In addition, we do not want to consider how to generate this identity attribute, we will configure Hibernate's identifier generation policy (identifier generation strategy) to produce surrogate primary keys.

The ID element is the declaration of the Identity attribute (Identifer property), name= "id" declares the name of the Java attribute (property)-Hibernate will use getId () and setId () to interview it. The field parameter (column attribute) tells hibernate which field of the EVENTS table is used as the primary key. Nested generator elements Specify the generation strategy for identifiers-here we use increment, which is a very easy way to generate numbers directly in memory, mostly in a test (or tutorial). Hibernate also supports the use of database generated, global uniqueness (globally unique), and application designation (application assigned). (or you can create an identifier yourself for any extension that has been written for whatever policy you already have).

Finally, we must also include in the mapping file a declaration that requires a persisted property. By default, properties inside a class are considered non-persistent:

 Hibernate official Beginner Tutorial (reprint) 

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.