The very detailed hibernate environment constructs "the diagram course" and the simple use

Source: Internet
Author: User
Tags documentation file copy postgresql prepare jboss tomcat log4j

Hibernate environment to build a "graphic tutorial"


The environment can be built simply to import the relevant jar package.

But for learning, the content of this environment is still quite a lot of, the purpose is to provide a let us how to quickly learn and master the class library of the learning environment. As a program ape, learning and using class libraries is a skill that must be mastered. How to quickly learn and use the class library, here are a lot of experience and skills. For example, refer to the official documentation tutorials, APIs, add to the IDE such as Javadoc support, and so on.

Official documents are the most important means and ways to learn a class library, and the authors of books and blog tutorials Learn these classes based on official documents. The official documentation provides the most up-to-date, systematic, and accurate learning materials. Although many of these documents are in English, this is not the reason why we don't look at the documents. Maybe you don't speak English very well, but a lot of people are like you, like me. Even so, I still adhere to the official document, prepare an electronic dictionary, I use the Bing dictionary, every time I met the word, I check, and add to the new words, gradually some of the documents I can understand the beginning.

From my self-study of the first Java class Library httpclient, to now (half a year) I self-study Jsoup, FileUpload, Jquery, Highcharts and so on. Although I cannot say that I have thoroughly digested these, it is no problem to realize some simple functions. Ask me how--put an API document folder on the desktop. There should be a folder for every programmer's desktop.


Today, for you to introduce hibernate environment, and not just to import a few jar bags, I am a library of learning some of the experience to share to everyone, give people to fish, rather than teach people to catch.

1. Don't be afraid of something new, because as a program ape, you can only keep learning. When we have learned a few classes of libraries, we will have some experience, and will find the fun of learning a new thing-the sense of accomplishment.

2. The most important thing is to prepare an electronic dictionary in the light of official documents. Add Javadoc to the IDE, reference API documentation, and more.

3. Do not memorize, prepare a notebook. Some of the thinking of things, we can be recorded in the notebook, as for class Library classes, methods we mainly refer to API documentation.

4. Do not blindly looking for Baidu, time-consuming and laborious, and many of the tutorials on Baidu is behind us for a long time old version, sometimes there will be some problems.

5. Do not impetuous, the more anxious the more mistakes, learning is a gradual accumulation of the process.

Download and understand its document structure

Hibernate3.6.10 Download Address

http://sourceforge.net/projects/hibernate/files/hibernate3/3.6.10.Final/


The download file is: Hibernate-distribution-3.6.10.final-dist.zip, the explanation of the filename is hibernate3.6.10 final release version.

The unpacked directory is as follows


The red line above is what we pay special attention to:

Documentation is a Help document

Project is the source code

Hibernate3.jar is the hibernate core Jar package, and Lib is the support jar package required by hibernate.

Documentation Help Document

We look at the document first, is documentation, the following red line is what we have to see.


Enter Documentation\manual\zh-cn\pdf


Look at this is God horse, yes is the Chinese help document, haha. Put it first, then look again!


Go back to the starting point and enter the Documentation\javadocs


Click Index.html to enter the Hibernate API help document


Import Jar Packs

To create a new Web project xhibernate, we need to import:

Hibernate3.jar

All jar packages in the required folder under the Lib directory

Database connection drivers, such as MySQL need: Mysql-connector-java-5.1.36-bin.jar


1. Copy the jar package above to the Webroot/web-inf/lib directory under the Xhibernate project


2.Build Path

Between this, the refresh presses the F5 refresh.

Right-click the newly created project and choose Build Path--Configure build path .... Enter the Java build path entry.


Here's a tip, hold down the CTRL or SHIFT key to be re-elected.


Join Source and Javadoc support

In the new good code, find a strange class such as session, and then hold down the CTRL key left click the session class, come to the code did not find the page


Select Attach Source ... Then select External Folder ...


Select the Hibernate folder you just unzipped, and the import source and Javadoc succeeded


Import a good later use

When the mouse points to a method of a class, there is a detailed explanation of the method. Very useful when coding!

For example, point to Session.save (user);


So far, hibernate environment to complete.


A simple Hibernate primer


In fact, hibernate itself is a stand-alone framework that does not require the support of any Web server or application server. However, most hibernate introductory introductions have added a lot of hibernate things, such as Tomcat, Eclipse, Log4j,struts, XDoclet, and even JBoss. This is easy to produce hibernate complex and difficult to understand the misunderstanding, especially the impact of the enthusiasm of beginners.

In this article will not involve Eclipse, log4j, Struts, Tomcat, XDoclet, and JBoss. The purpose of this article is to demonstrate the hibernate installation process as well as the most basic functions, so as to give beginners a low can not be lower entry threshold.


Download Files

You need the Java SDK, hibernate package, ant package, and JDBC Driver.

1, Hibernate package download Address:
Http://prdownloads.sourceforge.net/hibernate/?sort_by=date&sort=desc

2, ant package download Address:
Http://apache.130th.net/ant/binaries/apache-ant-1.6.1-bin.zip

3, JDBC driver according to your database to set, general database on the official website will have. Hibernate supports commonly used database, such as MySQL, Oracle, PostgreSQL, and Ms-sql Server. These databases all have JDBC Driver:

Oracle JDBC driver Download address (Oracle Agreement must be agreed before downloading)
Http://otn.oracle.com/software/htdocs/distlic.html?/software/tech/java/sqlj_jdbc/htdocs/jdbc9201.html

MySQL JDBC driver Download Address
Http://dev.mysql.com/downloads/connector/j/3.0.html

PostgreSQL JDBC driver Download Address
Http://jdbc.postgresql.org/download.html

Ms-sql Server JDBC driver download Address
http://www.microsoft.com/downloads/details.aspx?FamilyID=9f1874b6-f8e1-4bd6-947c-0fc5bf05bf71&displaylang=en

4, the Hibernate package and ant package extracted to c:/dev/(this directory is not important, you can change any other directory).

Configuring the Environment

1, you need to add a new environment variable: ant_home, let it point to c:/dev/< your ANT package directory >. and add%ant_home%/bin to the PATH environment variable.

2, you need to add a new environment variable: java_home, let it point to your J2SDK root directory. and add%java_home%/bin to the PATH environment variable.

3, create a project directory, such as C:/workspace/my1sthibernate.

In the project directory, create three additional directories: SRC, classes, lib.

In the Lib directory, create two directories: Hibernate and DB.

So you have the following file structure:

c:/workspace/my1sthibernate/
C:/workspace/my1sthibernate/src
C:/workspace/my1sthibernate/classes
C:/workspace/my1sthibernate/lib
C:/workspace/my1sthibernate/lib/hibernate
c:/workspace/my1sthibernate/lib/db

4, will c:/dev/< your hibernate package directory >/hibernate2.jar file copy to C:/workspace/my1sthibernate/lib/hibernate.

Copy all files under the directory >/lib/your hibernate package to c:/workspace/my1sthibernate/lib/hibernate under c:/dev/<.

Copy your JDBC driver file (typically a jar file) to c:/workspace/my1sthibernate/lib/db.


Creating a database

1, with your favorite database software, create a hibernate_test databases.

2. Under this database, create a new table named Customer

CREATE TABLE CUSTOMER
(
CID INTEGER not null PRIMARY KEY,
USERNAME VARCHAR (a) not NULL,
PASSW ORD VARCHAR ()
);


Writing Java files

public class customer {        private int id;
    private String username;
    private String password;     public int getid ()  {        
return id; &NBSP;&NBSP;&NBSP;&NBSP}     public string getpassword ()  {  
      return password; &NBSP;&NBSP;&NBSP;&NBSP}     public string getusername ()  {  
      return username; &NBSP;&NBSP;&NBSP;&NBSP}     public void setid (int id)  {  
      this.id = id; &NBSP;&NBSP;&NBSP;&NBSP}     public void setpassword (String password)   {        this.password = password; &NBSP;&NBSP;&NBSP;&NBSP}     public void setusername (String username)   {        this.username = username;     }}

The



saves this class as a C:/workspace/my1sthibernate/src/customer.java file.

Write test class

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*; public class test {    public static void main (String[)  args)  {        try {             sessionfactory sf =                  new configuration (). Configure ().
Buildsessionfactory ();             Session session = 
Sf.opensession ();             Transaction tx = 
Session.begintransaction ();             for  (int i = 0;  i < 200; i++)  {                  customer customer = new customer ();                 
Customer.setusername ("Customer"  + i);                 
Customer.setpassword ("Customer");                 session.save (
Customer);             }       
      tx.commit ();
            session.close ();         } catch  (hibernateexception e)  { 
           e.printstacktrace ();         }    &nbsp}}

The



saves this class as a C:/workspace/my1sthibernate/src/test.java file.


Create hibernate mapping file

Because there is only one class---customer and a table---customer, You only need to create a mapping file---Customer.hbm.xml to correspond to the relationship between the customer class and the Customer table.

<?xml version= "1.0"?> <! Doctype hibernate-mapping public      "-//hibernate/hibernate mapping  dtd//en "    " Http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd "> < Hibernate-mapping>     <class name= "Customer"  table= "Customer" >          <id name= "id"  column= "CID" >              <generator />          </id>         <property name= "username"   Column= "USERNAME"  />         <property name= "password"  column= "PASSWORD"  />     </class> 



Saves this file as C:/workspace/my1sthibernate/src/customer.hbm.xml, and Customer.java in the same directory.


to write an ant build.xml file

You don't have to know the details of this build.xml, but ant is not necessarily hibernate. Ant is used here to simplify tasks such as compiling, copy, running, and so on.

<?xml version= "1.0"  ?> <project name= "my1sthibernate"  default= "Build"  basedir ="." >     <property name= "Base.dir"  value= "."  />     <property name= "Src.dir"  value= "src"  />      <property name= "Lib.dir"  value= "Lib"  />     <property  name= "Build.dir"  value= "classes"  />     <path id= "Myclasspath" >         <fileset dir= "${lib.dir}" >              <include name= "**/*.jar"  />          </fileset>         < pathelement location= "${build.dir}"  />     </path>      <target name= "Init" >          <mkdir dir= "${build.dir}"  />     </ target>         <target name= "Build"  depends= "Init"   description= "Compile the source files" >         < javac classpathref= "Myclasspath"  srcdir= "${src.dir}"  destdir= "${build.dir}"  />          <copy todir= "${build.dir}"  >              <fileset dir= "${src.dir}"  >                  <exclude name= "**/*.java "/>             </fileset>          </copy>     </target>      <target name= "Run"  depends= "Build" >         <java  classpathref= "Myclasspath"  classname= "Test"  fork= "true"  />     </ target>     <target name= "clean" >          <delete includeemptydirs= "true" >              <fileset dir= "${build.dir}"  />         < /delete>     </target> </project>

The




configuration Hibernate description file

Hibernate description file can be a properties or XML file, the most important of which is to define a connection to the database. What I'm listing here is an XML-formatted hibernate.cfg.xml description file.

<?xml version= "1.0"  encoding= "Utf-8"  ?> <! Doctype hibernate-configuration     PUBLIC  "-//hibernate/hibernate  configuration dtd//en "    " http://hibernate.sourceforge.net/ Hibernate-configuration-2.0.dtd "> 



If you are not using Oracle 9i, locate your database in the directory >/src/hibernate.properties file of your hibernate package and replace the corresponding value c:/dev/<.


starts running

under C:/workspace/my1sthibernate and runs Ant run. If you follow these steps strictly, you should see

Run:
        [java] Log4j:warn No appenders could be Found for logger (net.sf.hibernate.cfg.Environment).
        [Java] Log4j:warn please initialize the log4j system properly.
        [Java] Hibernate:insert into CUSTOMER (USERNAME, PASSWORD, CID) VALUES ( ?, ?, ?)
Build Successful

Look at your hibernate_test database and add 200 new records to the Custmor table, but you didn't write any JDBC code.
If you want to replace the database later, just change the corresponding value in the Hibernate.cfg.xml description file.


Conclusion

This article is a very low threshold introductory introduction. I give a completely do not understand hibernate friend to see, he used in less than 30 minutes to run his first hibernate program, since then aroused his interest in hibernate. But readers must realize that this is only the beginning, and this is a glimpse of a small ice crystal in the corner of the hibernate iceberg. You can think of this as a starting point towards Hibernate Avenue.

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.