Hibernate学习一:配置及简单实例的创建过程

来源:互联网 发布:网络资金返还证书 编辑:程序博客网 时间:2024/05/17 05:50

Hibernate学习一:配置及简单实例的创建过程 收藏
文章主要内容来自http://www.jspcn.net/htmlnews/6008103182.html 的内容,将作者用的Oracle数据库换为mysql。

下载文件 需要Java SDK、 Hibernate包、Ant包、和JDBC Driver。

1、Hibernate包下载地址: https://www.hibernate.org/6.html 我下载的是  Hibernate Core 3.3.2.GA。

2、Ant包下载地址: http://ant.apache.org/bindownload.cgi  我下载的是apache-ant-1.7.1-bin.zip。

3、JDBC Driver要根据你用的database来定,一般database官方网站上都会有。 Hibernate支持常用的database,比如 MySQL, Oracle, PostgreSQL, 和MS-SQL Server。我用的是mysql。

MySQL JDBC Driver下载地址

http://dev.mysql.com/downloads/connector/j/5.1.html

4、将Hibernate包和Ant包分别解压至c:dev下(此目录不重要,你可以换其它任何目录)。

 

配置环境:

1、你需要添加一个新的环境变量:

ANT_HOME,让它指向c:/dev<你的ANT包所在目录>。并在PATH环境变量里添加%ANT_HOME%/bin。

2、你需要添加一个新的环境变量:

JAVA_HOME,让它指向你的j2sdk根目录。并在PATH环境变量里添加%JAVA_HOME%/bin。

3、创建一个项目目录,比如c:/workspace/My1stHibernate。 在项目目录下,另外创建三个目录: src, classes, lib。 在lib目录下,创建两个目录: hibernate和db。 这样你有了如下的文件结构:

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、将c:/dev<你的Hibernate包所在目录>

Hibernate3.jar文件copy到c:/workspace/My1stHibernate/lib/hibernate下。

将c:/dev<你的Hibernate包所在目录>lib 下的所有文件同样copy到c:/workspace/My1stHibernate/lib/hibernate下。

将你的JDBC Driver文件(一般是一个jar文件)copy到c:/workspace/My1stHibernate/lib/db下。 创建数据库

1、用你最喜爱的database软件,创建一个hibernate_test的数据库。 2、在此数据库下,新建一个table名为CUSTOMER.

Mysql创建步骤:

C:/Program Files/MySQL/MySQL Server 5.0/bin>net start mysql   启动数据库服务

在另一个cmd中连接数据库:mysql –uroot –p;输入密码。连接成功后用create database db创建数据库,用use db命令选择数据库,然后创建表CUSTOMER:

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


编写Java文件:

 view plaincopy to clipboardprint?
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;  
    }  

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;
 }
}

将此类存为c:/workspace/My1stHibernate/src/Customer.java文件。

编写Test类

 view plaincopy to clipboardprint?
import org.hibernate.*;   
import org.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 < 10; i++)  
            {    
                Customer customer = new Customer();  
                customer.setUsername("customer" + i);  
                customer.setPassword("customer");  
                session.save(customer);  
            }     
            tx.commit();   
            session.close();   
        }  
        catch (HibernateException e)   
        {   
            e.printStackTrace();   
        }   
    }  

import org.hibernate.*;
import org.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 < 10; i++)
   { 
    Customer customer = new Customer();
    customer.setUsername("customer" + i);
    customer.setPassword("customer");
    session.save(customer);
   }  
   tx.commit();
   session.close();
  }
  catch (HibernateException e)
  {
   e.printStackTrace();
  }
 }
}
 

将此类存为c:/workspace/My1stHibernate/src/Test.java文件。

创建Hibernate映射文件 因为这里只有一个Class --- Customer 和一个Table --- CUSTOMER,你只需要建立一个映射文件--- Customer.hbm.xml,来对应Customer类和CUSTOMER表之间的关系。

 view plaincopy to clipboardprint?
<?xml version="1.0"?> 
<!DOCTYPE hibernate-mapping PUBLIC  
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping>    
<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> </hibernate-mapping>  
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping> 
<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> </hibernate-mapping>
 

把此文件存为c:/workspace/My1stHibernate/src/Customer.hbm.xml,和Customer.java放在同一目录下。

编写Ant build.xml文件你不一定要知道这个build.xml的细节,其实Ant也不是Hibernate所必须的。这里用Ant是为了简化一些任务,比如: 编译、copy、运行等。

 view plaincopy to clipboardprint?
<?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> 
<?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> 

配置Hibernate描述文件 Hibernate描述文件可以是一个properties或xml文件,其中最重要的是定义数据库的连接。我这里列出的是一个XML格式的hibernate.cfg.xml描述文件。

 view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8" ?> 
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 
<hibernate-configuration> 
<session-factory name="java:/hibernate/HibernateFactory"> 
<property name="show_sql">true</property> 
<property name="connection.driver_class"> 
com.mysql.jdbc.Driver  
<!-- 这里是mysql的JDBC driver class名 --> 
</property> 
<property name="connection.url"> 
jdbc:mysql://localhost:3306/hibernate_test  
<!--这里是mysql的hibernate_test数据库URL --> 
</property> 
<property name="connection.username">      
root  
</property> 
<property name="connection.password"> 
root  
</property> 
<property name="dialect"> 
org.hibernate.dialect.MySQLDialect  
<!-- 这里是mysql的Dialect -->    
</property> 
<mapping resource="Customer.hbm.xml"/> 
<!-- 指定Customer的映射文件 -->   
</session-factory> 
</hibernate-configuration> 
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="java:/hibernate/HibernateFactory">
<property name="show_sql">true</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
<!-- 这里是mysql的JDBC driver class名 -->
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/hibernate_test
<!--这里是mysql的hibernate_test数据库URL -->
</property>
<property name="connection.username">   
root
</property>
<property name="connection.password">
root
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
<!-- 这里是mysql的Dialect --> 
</property>
<mapping resource="Customer.hbm.xml"/>
<!-- 指定Customer的映射文件 -->
</session-factory>
</hibernate-configuration>

开始运行到c:workspaceMy1stHibernate下,运行ant run。如果你严格依照以上步骤,应该看到 run:

Buildfile: build.xml

init:

build:

     [copy] Copying 1 file to E:/ProgramLib/MyHibernate/classes

run:

     [java] 15 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.2.GA

。。。。。。

     [java] Hibernate: select max(CID) from customer

     [java] Hibernate: insert into customer (username, password, CID) values (??, ?)

     [java] Hibernate: insert into customer (username, password, CID) values (??, ?)

     [java] Hibernate: insert into customer (username, password, CID) values (??, ?)

     [java] Hibernate: insert into customer (username, password, CID) values (??, ?)

。。。。。。

 

到你的hibernate_test数据库看一下,在CUSTMOR表里新添了10条记录,但你没有写任何JDBC code。以后如果你要更换数据库,只需要改变hibernate.cfg.xml描述文件里相应的值即可。

 

结论 此文是一篇门槛极低的入门介绍。我给一个完全不懂Hibernate的朋友看,他用了不到30分钟就运行了他的第一个Hibernate程序,从此引起了 他对Hibernate的兴趣。但读者必须认识到这只是一个开始,此文实乃窥Hibernate冰山一角上的一颗小冰晶。千里之行始于足下,你可以把此文章当迈向Hibernate大道的一个起点。

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/llqkk/archive/2009/12/06/4950167.aspx