Java Open Source project Hibernate Quick Start

Source: Internet
Author: User
Tags add file copy sql mysql net string version variable
QuickStart | Project Java Open source project Hibernate QuickStart In fact, the 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, 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.

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 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 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" >

<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 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>
Configure Hibernate description File

The hibernate description file 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!--This is the Oracle 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!--This is the Oracle 9i dialect-->
</property>

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

</session-factory>

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

Start running

Under C:\workspace\My1stHibernate, run Ant run. If you follow these steps strictly, you should see

Run
[Java] Log4j:warn No Appenders could is 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.

In the future, if you want to change the database, you just need to alter the corresponding value in the Hibernate.cfg.xml description file.



Related Article

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.