"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 built the basic Hibernate development environment. and made a simple example, the basic principle of it has a rational understanding.

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), and then from relationships to objects. Believe that a lot of people with small make up a problem, see the concept of headache. The following small series drew a picture to deepen understanding.

This diagram is particularly simple: Originally, without hibernate, we had to manipulate the database by jdbc+ manually writing SQL statements. Now, with hibernate, it has a highly encapsulated jdbc+sql, and we don't have to deal with complex SQL, 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. In the future, it will be 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, including 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 of the table field and 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 pretty much, in fact very few, the basic mapping is very easy. We mainly learn about relational 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 that uses XML to configure the mappings, such as 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. Using annotations to complete the 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, provided the database supports the sequence.

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. Different meanings are empty, username only 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: Because the primary key is changed to self-growth. So the data type is changed into int type

<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. Establish client class client. Adding 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 data generated by the database table, for example, as seen in:

The pros and cons of annotations and XML files. There are a lot of online, interested in being able to check, the small part is no longer tired of the statement, but small series feel. It is best not to use annotations at the beginning of the study, not easy to understand hibernate principles, and annotations for the extensibility of the program. It's too bad.

Next blog post. We introduce Hibernate's seven relational mappings, which are exceptionally simple and 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.