"SSH Advanced Path" Hibernate basic mapping (iii)

Source: Internet
Author: User

"SSH Advanced Path" Hibernate fundamentals (i) , the small series introduces the basic principles of hibernate and its core. Using the object-oriented thinking operation relational database.

"SSH Advanced path" hibernate build development environment + Simple example (ii) . The small series builds the basic hibernate development environment, and makes a simple example. Has a rational understanding of its basic principles.

This blog introduces the classic content of Hibernate: Object Relational mapping. It mainly introduces the basic concept of mapping. Map the classification, mapping file.

Concept

An ORM (Object Relational Mapping), which is a relational mapping of objects. Its role is to make a mapping between the relational database and the object. Maps from objects (object) to Relationships (Relation). The relationship is then mapped to the object. I believe that a lot of people and small make up a problem, see the concept of headache, the following small series of drawings to deepen understanding.

This is a very simple picture: Originally, without hibernate, we had to manipulate the database by jdbc+ manually writing SQL statements, and now we have hibernate. It's a highly encapsulated jdbc+sql, and we don't have to deal with complex SQL anymore, just manipulate the database just as you would an object.

The realization of ORM is to map the data of tables in the database into objects, Hibernate can enable us to use the object-oriented thinking operation relational database.

mapping files

The main files that Hibernate uses when implementing ORM functions are:
1, mapping Class (*.java): It is a description of the structure of the database table. The fields in the table are described as attributes in the class, and in the future it is possible to map the records in the table into objects of that class.

2. mapping file (*.hbm.xml): It is the relationship between the specified database table and the mapping class. Contains the corresponding relationship between the mapping class and the database table, the corresponding relationship of the table field and Class property type, and the corresponding relationship between the table field and the Class property name.

3. Hibernate core configuration file (*.properties/*.cfg.xml): It specifies some of hibernate's core configurations, including connection information that is required to connect to the database, such as which database to connect to, the username to log in to the database, Login password, connection strings, and so on. The address information for the mapping file is also placed here.

Classification

The above content looks very much, in fact very few, the basic mapping is very easy, we mainly learn the correlation relation mapping. Other kinds of mappings generally do not use, just need to understand, you can use the time to look at the relevant information will do just fine.

Basic mapping

Previous blog post we have implemented a basic mapping. is to use XML to configure the mappings, as seen in the following:

<span style= "FONT-SIZE:12PX;" ><?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

In addition to XML configuration mappings, you can configure mappings by adding annotations to class files. On the basis of the previous blog post. We made a slight change.

1. Add Hibernate annotion Support Package

*hibernate-annotations.jar
*hibernate-commons-annotations.jar
*ejb3-persistence.jar

What you see:

2, establish the entity class user, the use of annotations completed mapping

Package Com.liang.hibernate;import Java.util.date;import Javax.persistence.column;import javax.persistence.Entity; Import Javax.persistence.generatedvalue;import Javax.persistence.generationtype;import javax.persistence.Id; Import Javax.persistence.temporal;import Javax.persistence.TemporalType; @Entity//Do not write Table default feel user, @Table (name= "T_ User ") public class User {@Id//primary key @generatedvalue (Strategy=generationtype.auto)//Adopt database Self-increment mode to generate primary key// The four standard usage methods provided by JPA are table,sequence,identity,auto. Table: Use a specific database table to hold the primary key. SEQUENCE: Generates a primary key based on the sequence of the underlying database. The condition is that the database supports sequences. IDENTITY: The primary key is generated by the database itself (mainly self-growing)//auto: The primary key is controlled by the program. private int id;private string name;private string password; @Temporal (temporaltype.date)//Date of generation YYYY-MM-DD type private Date createtime; @Temporal (temporaltype.date)//generation of YYYY-MM-DD type dates private date expiretime;public int getId () {return ID;} public void setId (int id) {this.id = ID;} @Column (name= "name", Unique=true,nullable=false)//field is name, does not agree to be empty, username unique public String getName () {return name;} public void SetName (string name) {this.name = name;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} Public Date Getcreatetime () {return createtime;} public void Setcreatetime (Date createtime) {this.createtime = Createtime;} Public Date Getexpiretime () {return expiretime;} public void Setexpiretime (Date expiretime) {this.expiretime = Expiretime;}}

Note: The data type is changed to int type because the primary key is changed to self-growth

3, provide the Hibernate.cfg.xml file, add the entity class user to the Hibernate.cfg.xml configuration file. Complete Basic Configuration

<span style= "FONT-SIZE:12PX;" ><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "http// Hibernate.sourceforge.net/hibernate-configuration-3.0.dtd ">

4, write the tool class Exportdb.java, note generation DDL, must adopt Annotationconfiguration class

<span style= "FONT-SIZE:12PX;" >package Com.liang.hibernate;import Org.hibernate.cfg.annotationconfiguration;import Org.hibernate.cfg.configuration;import org.hibernate.tool.hbm2ddl.schemaexport;/** * Generate DDL for HBM * @author Liang * */ public class Exportdb{public static void Main (String[]args) {//default read hibernate.cfg.xml file configuration cfg = new Annotationconfiguration (). Configure (); Schemaexport export = new Schemaexport (CFG); Export.create (true, True);}} </span>

What the Database generation table sees:



5, Build client class client, add user data to MySQL

Package Com.liang.hibernate;import Java.util.date;import Org.hibernate.session;import org.hibernate.SessionFactory ; Import Org.hibernate.cfg.annotationconfiguration;import Org.hibernate.cfg.configuration;public class Client { public static void Main (String[]args) {//Read Hibernate.cfg.xml file configuration cfg = new Annotationconfiguration (). Configure ();//Establish Sessionfactorysessionfactory factory =cfg.buildsessionfactory ();//Get sessionsession session = NULL; try{//Open sessionsession = Factory.opensession ();//Open transaction session.begintransaction (); User user = new user (), User.setname ("Jiuqiyuliang"), User.setpassword ("123456"); User.setcreatetime (new Date ()); User.setexpiretime (New Date ());//Save User Object Session.save (user);//COMMIT Transaction session.gettransaction (). commit ();} catch (Exception e) {e.printstacktrace ();//ROLLBACK TRANSACTION session.gettransaction (). rollback ();} Finally{if (Session! = NULL) {if (Session.isopen ()) {///close Sessionsession.close ();}}}}

After execution, the database table generates the data, for example, as seen in:

The pros and cons of annotations and XML files are very much on the web and are interested to check it out. The small part is no longer tired of the statement. But Xiao-bian felt. It is best not to use annotations at the beginning of the study, it is not easy to understand the principles of hibernate, and annotations are too poor for the extensibility of the program.

In the next blog post, we introduce seven relational mappings for hibernate. Exceptionally simple. Thank you for your attention.

"SSH Advanced Path" Hibernate basic mapping (iii)

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.