my first hibernate practice

hibernate 3.1 alpha1+mysql4.1+jdk1.5.0004

1.目录结构
+My1stHibernate
   --build.xml
   +lib
      所需要的库:asm.jar,cglib-2.1.1.jar,commons-collections-2.1.1.jar,commons-logging-1.0.4.jar,dom4j-1.6.jar,ehcache-1.1.jar,hibernate3.jar,jta.jar,log4j-1.2.9.jar,mysql-connector-java-3.1.10-bin.jar
   +src
      --Customer.java
      --Customer.hbm.xml
      --Test.java
      --hibernate.cfg.xml
      --log4j.properties
    
2. 一个往数据库中存储客户信息的简单程序
客户实体类
<Customer.java>

public class Customer {
    
private int id;
    
private String username;
    
private String password;
    
    
public int getId()
    
{
        
return id;
    }

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

    
    
public String getPassword()
    
{
        
return password;
    }

    
    
public void setPassword(String password)
    
{
        
this.password=password;
    }

    
    
public String getUsername()
    
{
        
return username;
    }

    
    
public void setUsername(String username)
    
{
        
this.username=username;
    }

}

客户实体类对应的Hibernate映射文件
<Customer.hbm.xml>

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//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>


测试类
<Test.java>

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

    }

}

Hibernate的配置文件
<hibernate.cfg.xml>

<?xml version="1.0" encoding="utf-8" ?> 
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//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">
            org.gjt.mm.mysql.Driver 
        
</property> 
        
<property name="connection.url">
            jdbc:mysql://localhost:3306/test
        
</property>  
        
<property name="connection.username">    
            root 
        
</property> 
        
<property name="connection.password">
            root  
        
</property>
        
<property name="dialect"> 
            org.hibernate.dialect.MySQLDialect 
        
</property>  
        
<mapping resource="Customer.hbm.xml" /> 
    
</session-factory> 
</hibernate-configuration>


3. 建立数据库
在MySQL中建立一个名为test的数据库, 再在test中建一个表customer:

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

4. 还要增加一个文件
<log4j.properties>
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=warn, stdout

log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug

### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug

### log just the SQL
#log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug

### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug

### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug

### log cache activity ###
#log4j.logger.org.hibernate.cache=debug

### log transaction activity
#log4j.logger.org.hibernate.transaction=debug

### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug

### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace

5. 最后便是编写build文件用以ant编译运行
<?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>
posted on 2005-07-31 14:31  dbzou  阅读(302)  评论(0编辑  收藏  举报