Hibernate's simplest tutorial

Source: Internet
Author: User
Tags jboss

In fact, hibernate itself is a stand-alone framework that does not require support from any Web server or application server. However, most of the hibernate introductory introductions include many non-hibernate items, such as Tomcat, Eclipse, Log4j,struts, XDoclet, and even JBoss. This makes it easy for people to misunderstand the complexities of hibernate, especially when it strikes a beginner's enthusiasm.

In this article will not involve Eclipse, log4j, Struts, Tomcat, XDoclet, and JBoss. The purpose of this article is to demonstrate Hibernate's installation process and the most basic features, giving beginners a low-down entry threshold.


Download File

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

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

2. Ant Pack:
Http://apache.130th.net/ant/binaries/apache-ant-1.6.1-bin.zip

3, JDBC driver to be based on the database you use to set, the 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 (must agree to Oracle agreement before downloading)
Http://otn.oracle.com/software/htdocs/distlic.html?/software/tech/java/sqlj_jdbc/htdocs/jdbc9201.html

MySQL JDBC Driver
Http://dev.mysql.com/downloads/connector/j/3.0.html

PostgreSQL JDBC Driver
Http://jdbc.postgresql.org/download.html

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

4. Extract the hibernate packet and ant package separately 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, point it to c:/dev/< the directory where your ANT package is located >. 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 another three 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. Copy the directory >/hibernate2.jar file where your hibernate package is c:/dev/< to c:/workspace/my1sthibernate/lib/hibernate.

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

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


Create a database

1, use your favorite database software, create a hibernate_test.

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

CREATE TABLE CUSTOMER
(
CID INTEGER not NULL PRIMARY KEY,
USERNAME VARCHAR () not NULL,
PASSWORD VARCHAR (12)
);


Writing Java files

public class Customer {

private int id;
Private String username;
private String password;


public int getId () {
return ID;
}

Public String GetPassword () {
return password;
}

Public String GetUserName () {
return username;
}

public void setId (int id) {
This.id = ID;
}

public void SetPassword (String password) {
This.password = password;
}

public void Setusername (String username) {
This.username = Username;
}

}

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

Writing the 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 <; i++) {
Customer customer = new Customer ();
Customer.setusername ("customer" + i);
Customer.setpassword ("Customer");
Session.save (customer);
}

Tx.commit ();
Session.close ();

} catch (Hibernateexception e) {
E.printstacktrace ();
}
}
}

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


creating hibernate mapping Files

Because there is only one class---customer and one 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" >

<class name= "Customer" table= "Customer" >
<id name= "id" column= "CID" >
<generator class= "Increment"/>
</id>
<property name= "username" column= "username"/>
<property name= "password" column= "password"/>
</class>

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


Writing ant build.xml files


You don't have to know the details of this build.xml, but Ant is not a must for 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>


Configuring the Hibernate description file

Hibernate profiles can be a properties or XML file, the most important of which is to define the 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" >


<session-factory name= "Java:/hibernate/hibernatefactory" >

<property name= "Show_sql" >true</property>
<property name= "Connection.driver_class" >
Oracle.jdbc.driver.OracleDriver <!--This is the Oracle 9i JDBC Driver class name--
</property>
<property name= "Connection.url" >
Jdbc:oracle:oci8: @hibernate_test <!--here is Oracle's hibernate_test database URL--
</property>
<property name= "Connection.username" >
Your database user name
</property>
<property name= "Connection.password" >
Your database Password
</property>
<property name= "dialect" >
Net.sf.hibernate.dialect.Oracle9Dialect <!--here is dialect of Oracle 9i
</property>

<mapping resource= "Customer.hbm.xml"/> <!--Specify a mapping file for Customer--

</session-factory>


If you are not using Oracle 9i, you can find your database in the directory >/src/hibernate.properties file where your hibernate package is located, and then replace the values that correspond to the c:/dev/<.


Start Running

Under C:/workspace/my1sthibernate, run Ant run. If you follow the above steps strictly, you should see

Run
[Java] Log4j:warn No Appenders could is found for logger (net.sf.hibernate.cfg.Environment).
[Java] Log4j:warn initialize the log4j system properly.
[Java] Hibernate:insert into CUSTOMER (USERNAME, PASSWORD, CID) VALUES (?,?,?)
BUILD Successful

Take a look at your Hibernate_test database and add 200 new records to the Custmor table, but you didn't write any JDBC code.
In the future, if you want to change the database, you only need to alter the corresponding value in the Hibernate.cfg.xml description file.


Conclusion

This article is a very low threshold introduction. I gave a friend who knew nothing about hibernate, and he took less than 30 minutes to run his first hibernate program, which aroused his interest in hibernate. But the reader must realize that this is only the beginning, and this is a small ice crystal on the tip of hibernate iceberg. You can take this as a starting point towards the Hibernate boulevard.

Hibernate's simplest tutorial

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.