Hibernate实践(二)

类别:Java 点击:0 评论:0 推荐:

一个最简单的Hibernate sample;

1. 建表
CREATE DATABASE test;
USE test;

DROP TABLE IF EXISTS cat;
CREATE TABLE `cat` (
  `CatID` varchar(32) NOT NULL default '0',
  `name` varchar(32) default NULL,
  PRIMARY KEY  (`CatID`)
) TYPE=MyISAM;

INSERT INTO cat VALUES ('01001','Tomy');
INSERT INTO cat VALUES ('01002','Jacky');
INSERT INTO cat VALUES ('01003','Sunny');
INSERT INTO cat VALUES ('01004','Cherry');
INSERT INTO cat VALUES ('01005','Rubbish');

2. 创建配置文件
 1) Cat.hbm.xml
     <?xml version="1.0"?>
     <!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
   
     <hibernate-mapping>
     <class name="Cats" table="cat">
      <id name="catId" type="java.lang.String" column="CatID">
        <generator class="assigned" />
      </id>
     <property name="name" type="java.lang.String"  column="name" length="32" />
    </class>
   </hibernate-mapping>
     该记录只有两个field,CatID和name,CatID是主键。
 2) hibernate.cfg.xml
    <hibernate-configuration>
      <session-factory>
         <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
         <property name="hibernate.connection.username">******</property>
         <property name="hibernate.connection.password">******</property>
         <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
         <property name="show_sql">false</property>

         <!-- Mapping files -->
         <mapping resource="Cat.hbm.xml"/>
       </session-factory>
     </hibernate-configuration>

3. 代码
  1) Cats.java
      对象关系映射Class
  2) HibernateUtil.java
      封装了Hibernate的一些操作的class,按照Hibernate Ref上面的写的。
  3) Test.java
      一些简单的数据操作。

4. build.xml文件。

5. 目录结构
    .\Hibernate\build.xml
    .\Hibernate\src 
    .\Hibernate\lib 
    .\Hibernate\classes

6. 运行ant,ant 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] Find Cat :01004  Cherry
    [java] --------------- Query All --------------
    [java] Find Cat :01004  Cherry
    [java] Find Cat :01001  Tomy
    [java] Find Cat :01002  Jacky
    [java] Find Cat :01003  Sunny
    [java] Find Cat :01004  Cherry
    [java] Find Cat :01005  Rubbish

7. source code
    Hibernate.rar

本文地址:http://com.8s8s.com/it/it11367.htm