The most detailed illustrated tutorial in the history of hibernate+junit--from environment configuration to getting Started

Source: Internet
Author: User

Project catalog structure at the end
Eclipse Version: Mars 4.5.2
Database: Mysql+navicat

1. Requires hibernate Tools for Eclipse plugins

Download the tools that correspond to your version of Eclipse in JBoss tools. For easy construction of hibernate works.

When a good version is selected, an interface appears:

Just drag the link (the red circle) into eclipse.

After you have obtained the resources, click Finish to install them online:

A warning may pop up in the middle, ignoring that it will restart after loading:

The user experience will pop up after reboot:

Then we can see the Hibernate option in the File->new:

2. Download the JDBC driver

I use MySQL database, download MySQL JDBC on official website

It's good to extract the jar package.

3. Download Hibernate package

Download on hibernate website:

About 100M, extracted after downloading:

All jar packages under the folder are required.

4. Download JUnit

JUnit's jar pack is a lot to download, and I'm using version 4.10.

5. Create User Library

To facilitate the package, we create our own user library:

Under the windows-preference:

Introduce the JAR packages.

Next, create a new Java project

Under Engineering right Button – "Properties:

Click Next to select the desired custom library:

Then in the project will be more out of their own library:

It's not necessary to have a JUnit test unit on it.

6. Configuration Documentation

Create a new Cfg.xml file in the project SRC directory:

There may not be a hint before writing the code, and then find the hibernate download package:

This path has a DTD file, which is imported into eclipse:

Then write the document:

<?xml version= "1.0" encoding= "UTF-8"?><! DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://www.hibern Ate.org/dtd/hibernate-configuration-3.0.dtd "><hibernate-configuration>    <session-factory>        < property name="Connection.driver_class">Com.mysql.jdbc.Driver</Property >        < property name="Connection.url">Jdbc:mysql://localhost:3306/hibernate?useunicode=true&amp;characterencoding=utf-8</Property >        < property name="Connection.username">Root</Property >        < property name="Connection.password"></Property >        < property name="dialect">Org.hibernate.dialect.MySQLDialect</Property >        < property name="Show_sql">True</Property >        < property name="Format_sql">True</Property >        < property name="Hbm2ddl.auto">Create</Property >    </session-factory></hibernate-configuration>
7. Persistence class

Write an entity class in the SRC directory:

 Public  class Student {    /** * Comply with JAVABEAN requirements * 1. Common class * 2. Provides the default construction method of the public bag parameter 3. property to be privatized private 4. Properties to be encapsulated in Setter/getter */    Private intSidPrivateString name;PrivateString number; Public Student(){    } Public Student(intSid, String name, string number) {Super(); This. sid = Sid; This. name = name; This. Number = number; } Public int GetSID() {returnSid } Public void Setsid(intSID) { This. sid = Sid; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } PublicStringGetNumber() {returnNumber } Public void Setnumber(String number) { This. Number = number; }}
8. Create an object-relational mapping file

Also create a new Hbm.xml file:

Next, it will automatically help us generate the student Hbm.xml file:

<?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 2016-4-26 16:07:07 by Hibernate Tools 3.5.0.Final --<hibernate-mapping>    <class name="Student" table="Student">        <ID name="Sid" type="int">            <column name="SID" />            <generator class="Assigned" />        </ID>        < property name="name" type="java.lang.String">            <column name="name" />        </Property >        < property name="number" type="Java.lang.String" >            <column name="number" />        </Property >    </class></hibernate-mapping>

Then we'll introduce it into the Cfg.xml file, add a sentence:

<mapping resource="Student.hbm.xml"/>
9. Build a database

I use the navicat:

10. Using JUnit testing

Although it can be used without junit testing, he is more convenient.

First look at JUnit's three note tags: before,after,test: Each represents the execution of a test (typically initialized), after execution (typically destroying the resource) and executing the test code.

Build a Test folder in the project and write a Studenttest class:

ImportOrg.hibernate.Session;ImportOrg.hibernate.SessionFactory;ImportOrg.hibernate.Transaction;ImportOrg.hibernate.boot.Metadata;ImportOrg.hibernate.boot.MetadataSources;ImportOrg.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;ImportOrg.hibernate.boot.registry.StandardServiceRegistry;ImportOrg.hibernate.boot.registry.StandardServiceRegistryBuilder;ImportOrg.junit.After;ImportOrg.junit.Before;ImportOrg.junit.Test; Public  class studenttest {    / * * Test Student class */    PrivateSessionfactory sessionfactory;PrivateSession session;PrivateTransaction Transaction;@Before     Public void Init() {/** * Before using Serviceregistrybuilder, but after the hibernate4.3.x version * Serviceregistrybuilder obsolete, you can use Standardservice Registrybuilder Alternative, * but it's best to use the following method * *        //Create configuration Object        //configuration config = new Configuration (). Configure ();        //Create a service registration object        //Serviceregistry serviceregistry = new        //Serviceregistrybuilder (). Applysettings (Config.getproperties ()). build ();        //// Create session factory objects        //Sessionfactory = Config.buildsessionfactory (serviceregistry);        //// Session Object        //session = Sessionfactory.opensession ();        //// Open transaction        //Transaction = Session.begintransaction ();Standardserviceregistry Standardregistry =NewStandardserviceregistrybuilder (). Configure (). build (); Metadata Metadata =NewMetadatasources (standardregistry). Getmetadatabuilder (). Applyimplicitnamingstrategy (ImplicitNamingStrategyJ        pacompliantimpl.instance). build (); Sessionfactory = Metadata.getsessionfactorybuilder (). build ();//Session ObjectSession = Sessionfactory.opensession ();//Open transactionTransaction = Session.begintransaction (); }@After     Public void Destory() {//Commit transactions FirstTransaction.commit ();//Close SessionSession.close ();//Shut down session factorySessionfactory.close (); }@Test     Public void testsavestudent() {//Generate student ObjectsStudent s =NewStudent (1,"Jimo","0001"); Session.save (s);//Save object into Database}}

A closer look at the code above will tell you what hibernate does.

Now, proceed as shown:

Right-click to select JUnit Test:

The first time it might pop up:

Android development has been largely useless.

Then, the error, the reason is not found mapping corresponding resources, yes, we need to move the Student.hbm.xml file to the Cfg.xml file to find the place, so I moved to the same directory, so the complete directory of the final project is as follows:

Now look at the results of the JUnit test:

Print something out of the console:

Hibernate:Drop Table if existsStudenthibernate:Create TableSTUDENT (SIDinteger  not NULL, NAMEvarchar(255), Number varchar(255),Primary Key(SID)) April -, . 4: -: -Afternoon Org.hibernate.tool.Schema. Internal. Schemacreatorimpl applyImportSourcesINFO:HHH000476:Executing Import Script' Org.hiber[email protected]10fde30a 'Hibernate:Insert      intoSTUDENT (NAME, Number, SID)Values(?, ?, ?)

Then open the database, found a more student table (deceptive is the need to restart Navicat):

11. Summary

Perhaps, this is life, it is always difficult to start.

The most detailed illustrated tutorial in the history of hibernate+junit--from environment configuration to getting Started

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.