hiberante是对数据库持久层访问的一种机制,hibernate的应用可以使程序员将重点放到业务逻辑的实现上。hibernate的原理是将数据库结构封装,使程序员可以像使用普通对象一样调用数据库的相关接口,从实现数据库的相关操作。     下面就说一个例子,环境j2sdk1.4.2_04,tomcat4.1.27,eclipse3.0,hibernate2.1      数据库的结果如下:        create table Users (    LogonID VARCHAR(255) not null,    EmailAddress VARCHAR(255),    LastLogon DATE,    Password VARCHAR(255),    Name VARCHAR(255),    primary key (LogonID) ); 
create table Address2 (    ID VARCHAR(255) not null,    City VARCHAR(255),    State VARCHAR(255),    Zip VARCHAR(255),    primary key (ID) ); create table Contacts (    ID BIGINT not null,    EmailAddress VARCHAR(255),    Name VARCHAR(255),    User_ID VARCHAR(255),    primary key (ID) ); alter table Contacts add constraint FKE207C4735A7381EF foreign key (User_ID) references Users; create index IXE207C4735A7381EF on Contacts (User_ID); 
eclipse安装好hibernate插件后,许多比较繁琐,容易出错的配置文件,eclipse都可以帮您很好的自动生成 ,您的主要任务就是实现Dao,也就是eclipse针对每个表生成的数据访问对象。比如本例的BaseAddress2DAO,ContactsDAO,UsersDAO,你可以修改这三个对象实现对Contacts,Users,Address2的相关操作。该例子的结构如下:
  
  其中Address2,Contacts,Users相当于实体bean,实现对数据表的映射。由于表Users和Contacts存在one-to-many关系,所以在Users.java的实现中将Contacts也作为一个对象属性。 private java.util.Set _contactsSet; /**   * Return the value associated with the column: ContactsSet   */  public java.util.Set getContactsSet () {   return this._contactsSet;  } 
 /**   * Set the value related to the column: ContactsSet   * @param _contactsSet the ContactsSet value   */  public void setContactsSet (java.util.Set _contactsSet) {   this._contactsSet = _contactsSet;  }    public void addToContactsSet (Object obj) {   if (null == this._contactsSet) this._contactsSet = new java.util.HashSet();   this._contactsSet.add(obj);  } 一般情况下,hibernate实现数据库的连接有两种方式,一种是借助web服务器的连接池,一种是自己配置连接参数文件。这里只介绍第二种方式: <hibernate-configuration>  <session-factory>   <!-- local connection properties -->   <!--数据库路径-->   <property name="hibernate.connection.url">    jdbc:jtds:sqlserver://192.198.64.168:1433;databasename=test;SelectMethod=Cursor   </property>   <!--连接驱动-->   <property name="hibernate.connection.driver_class">    net.sourceforge.jtds.jdbc.Driver   </property>   <property name="hibernate.connection.username">sa</property>   <property name="hibernate.connection.password">sasa</property>   <!-- property name="hibernate.connection.pool_size"></property -->   <!-- 数据库方言 -->   <property name="dialect">    net.sf.hibernate.dialect.SQLServerDialect   </property>   <property name="hibernate.show_sql">false</property>   <property name="hibernate.use_outer_join">true</property>   <!-- mapping 文件-->   <mapping resource="com/head/multi/Contacts.hbm" />   <mapping resource="com/head/multi/Users.hbm" />   <mapping resource="com/head/multi/Address2.hbm" />  </session-factory> </hibernate-configuration>
 
   
 
  |