Java基础知识:谈谈简单Hibernate入门

发表于:2008-4-16 11:16

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:网络转载

关于Serializable接口:
  Hibernate 并不要求持久化类必须实现java.io.Serializable接口,但是对于采用分布式结构的Java应用,当Java对象在不同的进程节点之间传输时,这个对象必须实现这个接口;如果希望对HttpSession中存放的Java对象进行持久化,那么这个Java对象必须实现Serializable接口。
  关于不带参数的构造方法:
  
  public Customers() {    }
  
  Hibernate要求持久化类必须提供一个不带参数的默认的构造方法,原因请参考相关资料。
  
  创建Mysql数据库
  数据库名称:netstroe
  Customer表DDL定义如下:CREATE TABLE `customers` ( `Id` bigint(20) NOT NULL default '0', `name` varchar(15) default NULL, `age` int(11) default NULL, PRIMARY KEY (`Id`)) TYPE=MyISAM;
  
  创建对象-关系映射文件
  创建对象-关系映射文件:Customers.hbm.xml
  代码如下:
  
     "-//Hibernate/Hibernate Mapping DTD 2.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" > 
       name="entity.Customers" 
   table="customers"> 
        name="id" 
     type="java.lang.Integer"  
    column="id"
    > 
      
    
        name="name" 
     type="java.lang.String" 
     column="name"  
    length="15" 
   /> 
      name="age"  
    type="int"  
    column="age" 
     length="11" 
   />
  
  引入Hibernate所需的jar包
  Hibernate2.jar、hibernate-tools.jar
  
  通过Hibernate API 访问MYSQL数据库
  创建业务逻辑类:useHibernate.java
  代码如下:
  package business;
  import entity.Customers;
  import net.sf.hibernate.Session;
  import net.sf.hibernate.SessionFactory;
  import net.sf.hibernate.Transaction;
  import net.sf.hibernate.cfg.Configuration;
  public class useHibernate {    
  public static SessionFactory sessionFactory;  
    /** 初始化Hibernate,创建SessionFactory实例 */    
  public void saveCustomers(Customers customers) throws Exception {   
       Configuration config = null;  
        config = new Configuration().configure();   
       // 创建一个SessionFactory 实例       
   sessionFactory = config.buildSessionFactory();    
      Session session = sessionFactory.openSession();  
        Transaction tx = null;     
     try {      
        /* 开始一个事务 */         
     tx = session.beginTransaction();        
      session.save(customers);          
    /* 提交事务 */           
   tx.commit();  
        } catch (Exception e) {     
         // TODO Auto-generated catch block          
    if (tx != null)             
     tx.rollback();          
    throw e;      
    } finally { 
             session.close();  
        }  
    }}
  
  测试Hibernate配置是否成功
  创建Junit测试:testhibernate.java
  有关Junit请参考相关资料:
  package test;
  import business.useHibernate;
  import entity.Customers;import junit.framework.TestCase;
    Customers customers = new Customers();       
   customers.setId(new Integer(330121));     
     customers.setAge(24);       
   customers.setName("huhpreal");   
       useHibernate usehibernate = new useHibernate();   
       try {          
    usehibernate.saveCustomers(customers);      
    } catch (Exception e) {           
   // TODO Auto-generated catch block           
   e.printStackTrace();     
     }   
   }}
  
  查看后台打印信息:
  (cfg.Environment           403 ) Hibernate 2.0.3
  (cfg.Environment           432 ) hibernate.properties not found
  (cfg.Environment           452 ) using CGLIB reflection optimizer
  (cfg.Environment           462 ) JVM proxy support: true
  (cfg.Configuration          703 ) Configuration resource: /hibernate.cfg.xml
  (cfg.Configuration          270 ) Mapping resource: hbm/Customers.hbm.xml
  (cfg.Binder             178 ) Mapping class: entity.Customers -> customers
  (cfg.Configuration          885 ) Configured SessionFactory: null
  (cfg.Configuration          492 ) processing one-to-many association mappings
  (cfg.Configuration          503 ) processing foreign key constraints
  (impl.SessionFactoryImpl       132 ) building session factory
  (dialect.Dialect           83 ) Using dialect: net.sf.hibernate.dialect.MySQLDialect
  (connection.DriverManagerConnectionProvider 41 ) Hibernate connection pool size: 20
  (connection.DriverManagerConnectionProvider 70 ) using driver: org.gjt.mm.mysql.Driver at URL: jdbc:mysql://localhost:3306/netstore
  (connection.DriverManagerConnectionProvider 71 ) connection properties: {useUnicode=true, user=root, password=123456, characterEncoding=gb2312}
  (impl.SessionFactoryImpl       162 ) Use outer join fetching: false
  (impl.SessionFactoryImpl       185 ) Use scrollable result sets: true
  (impl.SessionFactoryImpl       186 ) JDBC 2 max batch size: 15
  (impl.SessionFactoryImpl       194 ) echoing all SQL to stdout
  (impl.SessionFactoryObjectFactory  82 ) no JDNI name configured
  (impl.SessionFactoryImpl       269 ) Query language substitutions: {}
  
  Hibernate 配置使用成功
  
  查看数据库:
  
  插入成功!
22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号