天天看點

(轉載)eclipse搭建hibernate環境

1.開發環境

      Eclipse 3.2+MySQL 4.0.16+Hibernate3.0

     首先應該安裝好Eclipse和MySQL,此外準備好MySQL的JDBC Driver和Hibernate3.0,相關下載下傳位址如下:

      Eclipse SDK:

         http://www.eclipse.org/downloads/index.php  

        MySQL及MySQL的JDBC Driver:

            http://www.mysql.org

        Hibernate:

           http://www.hibernate.org

        此外我還安裝了Eclipse的一個Hibernate插件:

      Hibernate synchronizer

            http://hibernatesynch.sourceforge.net

        Plugin Search:

         http://eclipse-plugins.2y.net/eclipse/search.jsp  

        Hibernate synchronizer插件的安裝和配置有問題請直接Google。

      在工程中其實隻用到了Hibernate synchronizer插件的一部分功能,Hibernate依賴的相關jar包最好還是手動添加,因為最開始用Hibernate synchronizer添加時總是發生錯誤。

      将下載下傳的Mysql driver和Hibernate包解壓縮,我們需要的隻是裡面相關的jar,在Eclipse中建立Mysql_Driver和Hibernate兩個 user library,将mysql-connector-java-3.0.15-ga-bin.jar加入Mysql_Driver中,将 hibernate3.jar,

,log4j-1.2.11.jar,antlr-2.7.5H3.jar,asm.jar,asm-attrs.jar,cglib- 2.1.2.jar,commons-collections-2.1.1.jar,commons-logging-1.0.4.jar,dom4j- 1.6.1.jar,ehcache-1.1.jar,jta.jar加入到Hibernate中。

2.開始

在Mysql中建立test資料庫(Mysql其實有個空的test資料庫),然後建立下面的Table

create table user (

id int(10) not null auto_increment primary key,

name varchar(20) not null,

password varchar(20) not null,

email varchar(50),

address varchar(100)

)type=innodb;

建立Java Project,将Mysql_Driver,Hibernate兩個user library添加到該工程的java build path中。

建立與資料表對應的POJO類:User和Contact

package com.user;

public class User{

     private Integer id;

     private String name;

     private String password;

     private Contact contact;

public Integer getId() {

   return id;

}

public void setId(Integer id) {

   this.id = id;

}

public String getName() {

   return name;

}

public void setName(String name) {

   this.name = name;

}

public String getPassword() {

   return password;

}

public void setPassword(String password) {

   this.password = password;

}

public Contact getContact() {

   return contact;

}

public void setContact(Contact contact) {

   this.contact = contact;

}

}

package com.user;

public class Contact {

private String email;

     private String address;

public String getAddress() {

   return address;

}

public void setAddress(String address) {

   this.address = address;

}

public String getEmail() {

   return email;

}

public void setEmail(String email) {

   this.email = email;

}

}

之後可以用synchronizer插件生成Hibernate配置檔案和映射檔案(相關過程可以參考http://www.ideagrace.com/html/doc/2005/08/01/00315.html),不過映射檔案必須稍作修改。

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 >

   <!-- local connection properties -->

   <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>

   <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

   <property name="hibernate.connection.username"></property>

   <property name="hibernate.connection.password"></property>

   <!-- property name="hibernate.connection.pool_size"></property -->

   <!-- dialect for MySQL -->

         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

         <property name="hibernate.show_sql">True</property>

         <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

      <mapping resource="User.hbm.xml"/>

     </session-factory>

</hibernate-configuration>

User.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 package="com.user">

<class

   name="User"

   table="user"

>

   <id

    name="Id"

    type="integer"

    column="id"

   >

    <generator class="native"/>

   </id>

   <property

    name="Name"

    column="name"

    type="string"

    not-null="true"

    length="20"

   />

   <property

    name="Password"

    column="password"

    type="string"

    not-null="true"

    length="20"

   />

   <component name="Contact" class="Contact">

    <property

    name="Email"

    column="email"

    type="string"

    not-null="false"

    length="50"

   />

   <property

    name="Address"

    column="address"

    type="string"

    not-null="false"

    length="100"

   />

   </component>

</class>

</hibernate-mapping>

3.測試

添加一個測試類:HibernateTest

package com.user;

import java.util.List;

import java.util.ListIterator;

import org.hibernate.*;

import org.hibernate.cfg.*;

public class HibernateTest {

     public static void main(String[] args) throws HibernateException {

         SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

         //

         //testInsert(sessionFactory);

         //

         testQuery(sessionFactory);

         sessionFactory.close();

     }

     public static void testInsert( SessionFactory sessionFactory )throws HibernateException {

       Session session = sessionFactory.openSession();

         Transaction tx= session.beginTransaction();

         User user = new User();

         Contact contact=new Contact();

         contact.setEmail("email");

         contact.setAddress("address");

         user.setName("caterpillar");

         user.setPassword("password");

         user.setContact(contact);

         session.save(user);

         tx.commit();

         session.close();

         System.out.println("OK!");

    }

     public static void testQuery( SessionFactory sessionFactory )throws HibernateException {

      Session session = sessionFactory.openSession();

         Transaction tx= session.beginTransaction();

         User user = new User();

         Contact contact=new Contact();

         Query query=session.createQuery("from User as user");

         //query.setCharacter(1, 'M');

         List names =query.list();

         for(ListIterator it=names.listIterator();it.hasNext();){

            user= (User)it.next();

            System.out.println("Id: " + user.getId());

             System.out.println("name: " + user.getName());

             System.out.println("password: " + user.getPassword());

             if(user.getContact()!=null){

              if(user.getContact().getEmail()!=null){

               System.out.println("Email: " + user.getContact().getEmail());

              }

              if(user.getContact().getAddress()!=null){

               System.out.println("Address: " + user.getContact().getAddress());

              }

             }

         }

         tx.commit();

         session.close();

     }

}