Hibernate learning Notes (1) Hibernate configuration

Source: Internet
Author: User
Tags map class naming convention reflection

a preparatory work

First we will create a simple console-based (console-based) Hibernate application.

The first thing we do is create our development directory and put all the Java library files that need to be used. Unzip the hibernate release package downloaded from the Hibernate website and copy all the required library files to our project.
Learn to build user-library-hibernate and add the appropriate jar package

(a) Project right-click-buildpath-configure build Path-add Library


(b) Select User-library and create a new hibernate in it, named Hibernatelibraray

(c) Add hibernate-Required jar packages to the library


As of this writing, these are the minimum set of library files required for Hibernate to run (note that we have also copied the Hibernate3.jar, which is the most important file).
The version of Hibernate you are using may require more or less library files than this. See README.txt in the lib/directory in the release package for more information about the required and optional third-party library file (in fact, log4j is not a required library file, but is liked by many developers).

(d) Introduction of the JDBC driver package for SQL Server

Create a table in SQL Server Studentinfo



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


two Persistence class

Our first persistence class is a simple JavaBean class with some properties:

Package Com.model;public class Studentinfo {private int id;private string name;private int age;private String sex;//construction method Pu Blic Studentinfo () {}public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public String Getsex () {return sex;} public void Setsex (String sex) {this.sex = sex;}}

You can see that this class accesses the property (getter and setter method) using the standard JavaBean naming convention, while setting the access level of the Class attribute (field) to private.
This is a recommended design, but it is not required. Hibernate also has direct access to these field, while the benefit of using the access method (accessor) is to provide robustness when refactoring (robustness).
In order to instantiate the object of this class through the reflection mechanism (Reflection), we need to provide an argument-free constructor (No-argument constructor).
For a specific studentinfo, the id attribute holds the value of a unique identifier (identifier). If we want to use all the features that Hibernate provides,
Then all persisted entities (persistent entity) classes (which also include some secondary dependency classes) require one of these identifier attributes.
In fact, most applications, especially Web applications, need to differentiate objects by identifiers, so you should consider using the identifier attribute instead of treating it as a limitation.
However, we do not normally manipulate the identity of an object, so the access level of its setter method should be declared private. This way, only hibernate can assign an identifier value to an object when it is saved.
You can see that hibernate has direct access to public,private and protected access methods and field. So choosing which way is entirely up to you, you can make your choice match your application design.
All persistence classes (persistent classes) require a parameterless constructor, because hibernate must use the Java reflection mechanism to create objects for you.
The access level of the constructor (constructor) can be private, but when the runtime proxy is generated, it requires access control at least the package level.
This makes it more efficient to get data from a persisted class without the bytecode directive (bytecode instrumentation).

Next, we'll tell hibernate about this persistent class.


three-map file

Hibernate needs to know how to load (load) and store persisted classes of objects. This is where the hibernate mapping file works.
The mapping file tells hibernate which tables (table) should be accessed from the database and which fields (columns) should be used in the table.

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. It is used by your editor or IDE to automate those XML elements (element) and attributes (attribute) that are used for mapping.
You can also open dtd-in a text editor this is the simplest way to see all of the Elements and attribute, and view their default values as well as comments. Note Hibernate does not load the DTD file from the Web,
But it will first look in the classpath of the application. The DTD file is already included in the Hibernate3.jar and is also under the src/directory of the Hibernate release package.
To shorten the code length, we will omit the DTD declaration in a later example. Of course, in an actual application, the DTD declaration is mandatory.
A class element is included between the hibernate-mapping tag. All persisted entity classes (again, perhaps the next dependent class, or those secondary entities) need a mapping to map class objects to tables in the SQL database.

So far, we've told Hibernate how to persist objects of the Studentinfo class into the Studentinfo table of the database and how to load objects from the Studentinfo table to the Studentinfo class.
Each instance corresponds to a row in the database table. Now we will continue to discuss the mapping of the unique identifier property to the database table. In addition, since we do not care how to handle this identifier, we configure the hibernate identifier generation policy to generate the surrogate primary key field.

The ID element is the declaration of the identifier attribute, and the name= "id" declares the name of the Java attribute-hibernate accesses it using GetID () and SetID ().
The Column property tells Hibernate what field of the Studentinfo table we use as the primary key. The nested generator element specifies the identifier generation strategy, where we specify native,
It automatically chooses the best identifier generation strategy based on the configured database (dialect). Hibernate supports the generation of identifiers by database generation, global uniqueness (globally unique), and application designations (or extensions that you have written for any existing policies).

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


idAs with elements, property the attributes of an element name tell hibernate which getter and setter method to use. In this example, hibernate will look for getDate()/setDate() , as well getTitle()/setTitle() .

Why date property contains column attribute, and title not? Hibernate uses the attribute property name as the field name by default when the column JavaBean is not set. This works well for title . However, date is a reserved keyword in most databases, so we'd better map it to a different name.

Another interesting thing is that the title attribute lacks a type attribute. The type we declare and use in the mapping file is not the Java data type we expected, nor is it the data type of the SQL database. These types are called Hibernate mapping types (mapping types), which can convert Java data types to SQL data types and vice versa. Again, if the attribute is not set in the mapping file type , Hibernate will try to determine the correct type of conversion and its mapping type. In some cases this automatic detection mechanism (using the reflection mechanism on Java classes) does not produce the default values you expect or need. dateproperties are a good example, hibernate does not know whether the attribute ( java.util.Date type) should be mapped to: SQL date , or timestamp , or time field. In this example, the attribute is mapped to a timestamp converter so that we have all the information for the date and time.

This mapping file should be saved to the Event.hbm.xml source file directory of the studentinfo Java class. The mapping file can be arbitrarily named, but hbm.xml the suffix has become a convention for the hibernate developer community.

The configuration for Studentinfo is as follows:

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

We continue with the main configuration of hibernate.


Four Hibernate configuration

Now that we have a persistent class and its mapping file, it's time to configure Hibernate. Until then, we need a database.

Hibernate is the layer in your application that connects to the database, so it needs to connect with the information. The connection (connection) is done through a JDBC connection pool (connection pool) that is also configured by us.
Hibernate's release package contains a number of open source connection pools. Note that if you want to use a product-level (production-quality) third-party connection pooling software, you must copy the required library files to your classpath and use different connection pool settings.  
in order to save hibernate configuration, we can use a simple hibernate.properties file, or a slightly more complex hibernate.cfg.xml, or even fully use the program to configure Hibernate. Most users prefer to use XML configuration files:  

<?xml version= ' 1.0 ' encoding= ' utf-8 '? ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://hibernate. Sourceforge.net/hibernate-configuration-3.0.dtd ">
Note that this XML configuration uses a different DTD. Here, we configure Hibernate's sessionfactory-a factory (factory) that is associated with a specific database global.
If you want to use multiple databases, you need to use multiple <session-factory&gt, usually put them in multiple configuration files (for easier startup).
The first 4 property elements contain the necessary JDBC connection information. The property element of the dialect (dialect) indicates the specific SQL variables that hibernate generates. As you'll see soon, Hibernate's automatic session management of the persistence context will come in handy.
Opening the Hbm2ddl.auto option will automatically generate the database schema (schema)-directly into the database. Of course this option can also be turned off (by removing this configuration option) or by using the ant task Schemaexport Help to redirect the database schema to the file.
Finally, the mapping file is added to the persistence class in the configuration.







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.