Hibernate ORM Framework--First chapter: Hibernate Introduction and operational basics

Source: Internet
Author: User

I. Download and import of related usage tools (environment configuration)

hibernate-release-4.2.21.final--> old version
Hibernate-release-5.2.10.final--> new version

First need decompression: hibernate-release-5.2.10.final (new version)
--Copy all the jar packages from the Lib folder in the extracted Hibernate-release-5.2.10.final folder to the Lib folder under the root project, including the JDBC Ojdbc6.jar package
-Turn all jar packs into milk bottles

Unzip: Hibernate-tutorials file: Can be found in this file: basic--always go in.
Until you see the Java and Resources files, then select the XML header file that you want to have in the file according to the requirements

-->hibernate.cfg.xml (header file for configuration files)
<! DOCTYPE hibernate-configuration Public
"-//hibernate/hibernate Configuration DTD 3.0//en"
"Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
-->empmapping.xml (header file of the mapping file)
<! DOCTYPE hibernate-mapping Public
"-//hibernate/hibernate Mapping DTD 3.0//en"
"Http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >

Second, the first hibernate add an operation

1) using the PL/SQL database

2) First analogy native JDBC implementation add operation: (no need to encapsulate Util package)

Note: This code must first create the required tables in the database

2.1) analogy Jave native JDBC Implementation add operation

1.1 Util Package-->dbutils.java: Connect database driver

 PackageUtils;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.SQLException; Public classDbutils {Private Static FinalString url = "Jdbc:oracle:thin: @localhost: 1521:orcl"; Private Static FinalString username = "MyUser"; Private Static FinalString Password = "123";  Public StaticConnection getconnection ()throwsSQLException {returndrivermanager.getconnection (URL, username, password); }         Public Static voidCloseConnection (Connection conn)throwsSQLException {conn.close (); }    }

1.2 Write entity objects

 Package entity;  Public class testentity {    private  String name;      Public String GetName () {        return  name;    }      Public void setName (String name) {        this. Name = name;    }} 

1.3 Writing DAO Packages

 PackageDAO;Importjava.sql.Connection;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.util.ArrayList;Importjava.util.List;Importentity. testentity;ImportUtils. Dbutils; Public classTestdao { Public voidInsert (String name)throwssqlexception{Connection Conn=dbutils.getconnection (); String SQL= "INSERT INTO mytable values (?)"; PreparedStatement PS=conn.preparestatement (SQL); Ps.setstring (1, name);    Ps.executeupdate (); }             PublicList<testentity> GetAll ()throwsException {List<TestEntity> result =NewArraylist<testentity>(); Connection Conn=dbutils.getconnection (); String SQL= "SELECT * FROM MyTable"; PreparedStatement PS=conn.preparestatement (SQL); ResultSet RS=Ps.executequery ();  while(Rs.next ()) {testentity entity=Newtestentity (); Entity.setname (Rs.getstring (1));        Result.add (entity); }        returnresult; }}

1.4 Write Test Package

 PackageYuanmain;Importjava.util.List;ImportDAO. Testdao;Importentity. testentity; Public classYuanmain { Public Static voidMain (string[] args)throwsException {/* Follow the previous JDBC Add and query database operation*/        /*Add*/Testdao Testdao=NewTestdao (); //Testdao.insert ("xxttt");                        /*Enquiry*/List<TestEntity> all =Testdao.getall ();        System.out.println (All.size ());  for(testentity testentity:all) {System.out.println (Testentity.getname ()); }        }}

3) The first Hibernate implementation adds the operation code (optimizes the above analogy Java code)

3.1---first copy all the jar packages from the Lib folder in the extracted Hibernate-release-5.2.10.final folder to the Lib folder under the root project, including the JDBC Ojdbc6.jar package
-Turn all jar packs into milk bottles

Project structure:

3.2 Write code:

Configuration file

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-Configuration Public"-//hibernate/hibernate Configuration DTD 3.0//en" "Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" & gt;true</property> <!--display formatted SQL statements: Optimized typesetting--<property name= "Format_sql" >true</property> <!--datasheet map configuration file--<mapping resource= "Com/nf/personer.xml" ></mappin G> </session-factory> 

Entity objects:

 Packagecom.nf; Public classPersoner {Private Longpid; PrivateString pname;  Public LongGetpid () {returnpid; }     Public voidSetpid (Longpid) {         This. PID =pid; }     PublicString Getpname () {returnpname; }     Public voidsetpname (String pname) { This. pname =pname; }        }

Entity mapping File

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE hibernate-configuration        Public "-//hibernate/hibernate configuration DTD 3.0//en"         package = "COM.NF" >    <class name= "Personer" table= "personers" >        <id name= "pid" column= "id" >            <!--Identity primary key: Increment/native autogrow, assigned self-input-            class= "Increment" >< /generator>        </id>        <property name= "pname" ></property>    </class >

Test class

 Packagecom.nf;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;Importorg.hibernate.Transaction;Importorg.hibernate.boot.MetadataSources;ImportOrg.hibernate.boot.registry.StandardServiceRegistry;ImportOrg.hibernate.boot.registry.StandardServiceRegistryBuilder; Public classMain { Public Static voidMain (string[] args) {Standardserviceregistry Registry=Newstandardserviceregistrybuilder (). Configure (). build (); Sessionfactory SF=Newmetadatasources (registry). Buildmetadata (). Buildsessionfactory (); Session s=sf.opensession (); Personer PS=NewPersoner (); Ps.setpname ("XXX"); /*ps.setpname ("try");*/Transaction TS=s.begintransaction ();        S.save (PS);                Ts.commit ();        S.close ();    Sf.close (); }}

* * Above personal packing notes, if wrong or do not understand the place, welcome comments and points * *

Hibernate ORM Framework--First chapter: Hibernate Introduction and operational basics

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.