一.生成后的文件结构如下图


各文件内容如下:
二.配置文件
1.
hibernate.cfg.xml
<?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>
        
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        
<property name="hibernate.connection.password">1234</property>
        
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sample</property>
        
<property name="hibernate.connection.username">root</property>
        
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
<mapping resource="cn/blogjava/start/TUser.hbm.xml" />
    
</session-factory>
</hibernate-configuration>

2.
hibernate.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd" >

<hibernate-reverse-engineering>
  
<table-filter match-catalog="sample" match-name="t_user"/>
</hibernate-reverse-engineering>

3.
GeneralHbmSettings.hbm.xml
<?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>    
<!-- 
    Auto-generated mapping file from
    the hibernate.org cfg2hbm engine
    for General Global Setttings
-->

    
<import 
        
class="cn.blogjava.start.TUser"
        rename
="cn.blogjava.start.TUser"
    
/>
    

</hibernate-mapping>

4.TUser.hbm.xml
<?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>
<!-- 
        Auto-generated mapping file from
        the hibernate.org cfg2hbm engine
-->
    
<class name="cn.blogjava.start.TUser" table="t_user" catalog="sample">
        
<id name="id" type="integer">
            
<column name="id" />
            
<generator class="native" />
        
</id>
        
<property name="name" type="string">
            
<column name="name" length="100" not-null="true" />
        
</property>
    
</class>
</hibernate-mapping>

5.
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
=info, stdout

log4j.logger.org.hibernate
=error
#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

三.Java类
1.POJO类TUser.java
 1package cn.blogjava.start;
 2
 3
 4
 5/**
 6 * TUser generated by hbm2java
 7 */

 8
 9public class TUser  implements java.io.Serializable {
10
11
12    // Fields    
13
14     private Integer id;
15     private String name;
16
17
18    // Constructors
19
20    /** default constructor */
21    public TUser() {
22    }

23    
24    /** constructor with id */
25    public TUser(Integer id) {
26        this.id = id;
27    }

28
29    
30
31   
32    // Property accessors
33
34    public Integer getId() {
35        return this.id;
36    }

37    
38    public void setId(Integer id) {
39        this.id = id;
40    }

41
42    public String getName() {
43        return this.name;
44    }

45    
46    public void setName(String name) {
47        this.name = name;
48    }

49   
50
51
52
53
54
55
56
57
58}

2.测试类HibernateTest.java
  1package cn.blogjava.start;
  2
  3import java.util.List;
  4
  5import junit.framework.Assert;
  6import junit.framework.TestCase;
  7
  8import org.hibernate.HibernateException;
  9import org.hibernate.Session;
 10import org.hibernate.SessionFactory;
 11import org.hibernate.Transaction;
 12import org.hibernate.cfg.Configuration;
 13
 14
 15public class HibernateTest extends TestCase {
 16    
 17    Session session = null;
 18    /**
 19     * JUnit中的setUp方法在TestCase初始化的时候会自动调用
 20     * 一般用于初始化公用资源
 21     */

 22    protected void setUp() {
 23        try {
 24            /**
 25             * 可以采用hibernate.properties或者hibernate.cfg.xml
 26             * 配置文件的初始化代码
 27             * 
 28             * 采用hibernate.properties
 29             * Configuration config = new Configuration();
 30             * config.addClass(TUser.class);
 31             */

 32            
 33            //采用hibernate.cfg.xml配置文件,与上面的方法对比,两个差异
 34            //1.Configuration的初始化方式
 35            //2.xml
 36            Configuration config = new Configuration().configure();
 37            SessionFactory sessionFactory = config.buildSessionFactory();
 38            session = sessionFactory.openSession();
 39            
 40        }
 catch (HibernateException e) {
 41            // TODO: handle exception
 42            e.printStackTrace();
 43        }
        
 44    }

 45
 46    /**
 47     * JUnit中的tearDown方法在TestCase执行完毕的时候会自动调用
 48     * 一般用于释放资源
 49     */
    
 50    protected void tearDown() {
 51        try {
 52            session.close();        
 53        }
 catch (HibernateException e) {
 54            // TODO: handle exception
 55            e.printStackTrace();
 56        }
        
 57    }
    
 58    
 59    /**
 60     * 对象持久化测试(Insert方法)
 61     */
        
 62    public void testInsert() {
 63        Transaction tran = null;
 64        try {
 65            tran = session.beginTransaction();
 66            TUser user = new TUser();
 67            user.setName("byf");
 68            session.save(user);
 69            session.flush();
 70            tran.commit();
 71            Assert.assertEquals(user.getId().intValue()>0 ,true);
 72        }
 catch (HibernateException e) {
 73            // TODO: handle exception
 74            e.printStackTrace();
 75            Assert.fail(e.getMessage());
 76            if(tran != null{
 77                try {
 78                    tran.rollback();
 79                }
 catch (Exception e1) {
 80                    // TODO: handle exception
 81                    e1.printStackTrace();
 82                }

 83            }

 84        }

 85    }

 86    
 87    /**
 88     * 对象读取测试(Select方法)
 89     */
            
 90    public void testSelect(){
 91        String hql = " from TUser where name='byf'";
 92        try {
 93            List userList = session.createQuery(hql).list();
 94            TUser user = (TUser)userList.get(0);
 95            Assert.assertEquals(user.getName(), "byf");
 96        }
 catch (Exception e) {
 97            // TODO: handle exception
 98            e.printStackTrace();
 99            Assert.fail(e.getMessage());
100        }

101    }

102}

103
posted on 2006-07-05 14:37 knowhow 阅读(780) 评论(0)  编辑  收藏 所属分类: ORM:Hibernate及其他

只有注册用户登录后才能发表评论。


网站导航: