Hibernate4.3.2 + Mysql + eclipse配置

1. 首先在eclipse裏建立一個Java Project,命名爲HibernateFreshBird。在src的目錄下建立一個實體對象Person,包名爲com.hellopclee.hibernate.test

爲Person定義兩個屬性,id 和 name,併爲它們實現get和set方法。

package com.hellopclee.hibernate.test;

public class Person {

	int id;
	String name;
	public Person() {
		super();
	}
	public Person(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}
2. 到http://hibernate.org/orm/downloads/ 下載Hibernate的文件。我的版本是4.3.2,不同版本在配置上會有些小的變化。下載後解壓,把/lib/required目錄下的jar包加到HibernateFreshBird項目中來。爲了方便使用,可以定義User liberary。右鍵HibernateFreshBird項目,HibernateFreshBird -> Buid Path ->Configure Buid Path。選擇Add Library –> User Library,再點擊User Libraries -> New,新建一個自定義的Library,把名字命名爲HibernateLib,/lib/required目錄下的文件都添加進去。然後回到Add Library的對話框,把HibernateLib勾選上。點擊Finish。

3. 順便把Mysql的驅動也加到項目中來,方法同上。這時候你的項目應該是這個樣子的。

4.        在com.hellopclee.hibernate.test下再建立一個映射文件,命名爲person.hbm.xml,這個文件的作用是告訴定義數據庫中的表和Person類的映射關係。


<?xml version='1.0'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.hellopclee.hibernate.test">
	<class name="Person" table="person">
		<id name="id" type="int" column="Id">
			<generator class="assigned" />
		</id>

		<property name="name">
			<column name="Name" />
		</property>

	</class>
</hibernate-mapping>

5.        再在src下定義一個配置文件,定義HibernateFreshBird項目和數據庫的連接。例如我的數據庫用的是mysql,連接的是test這個schema, 用戶名是root,沒有密碼,還有告訴HibernateFreshBird通過person.hbm.xml 來建立映射關係。

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///test
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="com/hellopclee/hibernate/test/person.hbm.xml"/>
</session-factory>
</hibernate-configuration>

6.        在mysql裏建立一個表。

create table person (
	id int,
	name varchar(10)
)

7.        新建一個HibernateUtil,來初始化和數據庫的連接。

package com.hellopclee.hibernate.test;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
        	Configuration cfg = new Configuration().configure(); 
        	ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build(); 
        	SessionFactory sf = cfg.buildSessionFactory(serviceRegistry);
        	return sf;
        	
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

8.       現在就可以體驗hibernate的威力了。新建一個PersonDetail類,

package com.hellopclee.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.service.ServiceRegistry;

public class PersonDetail {
	private static SessionFactory sessionFactory;
	private static ServiceRegistry serviceRegistry;

	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Person person = new Person();
        person.setId(123);
        person.setName("pclee");
        session.save(person);

        session.getTransaction().commit();
        HibernateUtil.getSessionFactory().close();
	}
}

運行,你會發現在mysql的Person表裏多了一項,123:pclee。如果出錯,請根據提示信息作相應的修改。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章