The path of Hibernate learning (a)--helloworld

Source: Internet
Author: User

1. The software used:

(1) Eclipse Java EE IDE

(2) MySQL Database

The corresponding jar package is introduced in 2.eclipse:

1) Jar package with hibernate introduced in Build path

2) Introduction of MySQL Java-connected jar package

3. Write Hibernate configuration file

Name the file Hibernate.cfg.xml

1 <?XML version= "1.0" encoding= "UTF-8"?>2 3 <!DOCTYPE hibernate-configuration Public4 "-//hibernate/hibernate Configuration DTD 3.0//en"5 "Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">6         7 <hibernate-configuration>8 <session-factory>9     < Propertyname= "Connection.driver_class">Com.mysql.jdbc.Driver</ Property>Ten     < Propertyname= "Connection.username">Root</ Property> One     < Propertyname= "Connection.password"></ Property> A     < Propertyname= "Connection.url">Jdbc:mysql:///hibernate</ Property> -     < Propertyname= "dialect">Org.hibernate.dialect.MySQLDialect</ Property> -     < Propertyname= "Show_sql">True</ Property> the     < Propertyname= "Format_sql">True</ Property> -     < Propertyname= "Hbm2ddl.auto">Update</ Property> -     <MappingResource= "Com/denise/hibernate/model/student.hbm.xml" /> -     <Mappingclass= "Com.denise.hibernate.model.Teacher" /> + </session-factory> - </hibernate-configuration>

The properties of the Session-factory, Connection.username and Connection.password are the MySQL database's own user name and password, such as my username is root, the password is not set, and Connection.url indicates the address of the database, can be written in many forms, because I connect the number of It is the hibernate database under LocalHost, so the address can be abbreviated as above.

The last two mapping, is the mapping of the model, resource is the traditional way of mapping, followed by the address of the class file, class is the way to map with annotations, followed by the class name. For ease of understanding, you can first create a good model class and then write the clause.

4. Create the appropriate table for the database

Create two tables in the connected database, named student and teacher, respectively. Student field has ID name age,teacher field has ID name title, both table IDs are set as primary keys.

If you are using MySQL from the command line client, you can create it with the following SQL statement:

Use hibernate;

CREATE TABLE student (ID int primary key, name varchar (), age int);

CREATE TABLE teacher (ID int primary key, name varchar (), title varchar (10));

If you are using MySQL with a graphical interface, the creation process is simpler.

5. Create the model class for the corresponding database table

The first step in creating a Java class corresponding to a database table is to connect the database to the Java class, which is the mapping. There are two ways to map, one is to map files, and the other is to use annotation mappings. The student class adopts the former, and the teacher adopts the latter. Look at the difference between the two.

Student class:

1  PackageCom.denise.hibernate.model;2 3  Public classStudent {4     Private intID;5     PrivateString name;6     Private intAge ;7      Public intgetId () {8         returnID;9     }Ten      Public voidSetId (intID) { One          This. ID =ID; A     } -      PublicString GetName () { -         returnname; the     } -      Public voidsetName (String name) { -          This. Name =name; -     } +      Public intGetage () { -         returnAge ; +     } A      Public voidSetage (intAge ) { at          This. Age =Age ; -     } -      -}

Teacher Class:

1  PackageCom.denise.hibernate.model;2 3 Importjavax.persistence.Entity;4 Importjavax.persistence.Id;5 6 @Entity7  Public classTeacher {8     Private intID;9     PrivateString name;Ten     PrivateString title; One      A @Id -      Public intgetId () { -         returnID; the     } -      Public voidSetId (intID) { -          This. ID =ID; -     } +      PublicString GetName () { -         returnname; +     } A      Public voidsetName (String name) { at          This. Name =name; -     } -      PublicString GetTitle () { -         returntitle; -     } -      Public voidSettitle (String title) { in          This. title =title; -     } to  +}

Each property corresponds to each field in the table, where the field name is the same as the table name. Add the Setter getter method again.

6. Mapping

1) Mapping File mappings

Under Student A similar package, create a Student.hbm.xml

<?XML version= "1.0"?><!DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd "><!--Generated 2015-7-19 11:31:50 by Hibernate Tools 3.4.0.CR1 -<hibernate-mapping>    <classname= "Com.denise.hibernate.model.Student"Table= "STUDENT">    <!--database table names are case insensitive -        <IDname= "id"type= "int"> <!--Map PRIMARY Key -            <columnname= "ID" />            <Generatorclass= "Assigned" />        </ID>        < Propertyname= "Name"type= "Java.lang.String">            <columnname= "NAME" />        </ Property>        < Propertyname= "Age"type= "int">            <columnname= "Age" />        </ Property>    </class></hibernate-mapping>

In fact, the type here can be omitted. Colume name is the same as the table name and can also be omitted.

2) Annotation Map

No additional files need to be added.

7. Writing Test class tests

     Public voidmaintest () {Student s=NewStudent (); S.setid (002); S.setname ("Lily"); S.setage (33); Teacher T=NewTeacher (); T.setid (2011); T.setname ("Kim"); T.settitle (Intermediate); Configuration CFG=NewConfiguration (); Sessionfactory SF=cfg.configure (). Buildsessionfactory (); Session Session=sf.opensession ();        Session.begintransaction ();        Session.save (s);        Session.gettransaction (). commit ();        Session.close (); Sf.close ();}

At present, Buildsessionfactory has actually been discarded, the latest method can be easily found.

Run the method with JUnit and see if the data in the table is updated in the database.

In addition, the current order is, first build the table, then write the model class, the last mapping. In fact, the order can be adjusted, mainly to see the developer's own wishes.

Hibernate learning Path (i)--helloworld

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.