`
xuweijian2009
  • 浏览: 22917 次
  • 性别: Icon_minigender_1
  • 来自: 广州
最近访客 更多访客>>
社区版块
存档分类
最新评论

建立基础的Hibernate项目的过程

阅读更多
1.选择开发过程
  常见的开发场景
      自顶向下(top-down)
           在自顶向下的开发中,从一个现有的领域模型开始,使用java完成领域模型的实   现,并(理想地)完成数据库Schema方面的自主。
      自底向上(button—up)
         反之,自底向上开发始于一个现有的数据库Schema和数据模型。此时,最容易进行的方式就是使用反向工程工具从数据库中抽取元数据。
      起自中间层(middle out)
          Hibernate XML映射元数据提供充分的信息来完全推导出数据库Schema,并给应用的持久层生成java源代码。

2.建立项目基础
     2.1 创建工作目录
           * HIBERNATE_HOME/hibernate3.jar
   * HIBERNATE_HOME/lib/*.jar
   * MySql jdbc驱动
3.编写应用代码和映射
     3.1 创建领域模型
            Hibernate应用程序定义了被映射到数据库表的持久化类。你以业务领域的分析为基础定义了这些类,因此,它们是一个领域模型。“Hello World”实例由一个类和它的映射组成。
package com.xwj.model;

public class Message {

	private int id;
	private String text;
	private Message nextMessage;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	public Message getNextMessage() {
		return nextMessage;
	}
	public void setNextMessage(Message nextMessage) {
		this.nextMessage = nextMessage;
	}
}


    3.2 映射类到数据库Schema
           为了让对象/关系映射发挥神奇的魔力,Hibernate需要更多关于Message类究竟应该如何被持久化的信息。换句话说,Hibernate需要知道该类的实例要如何存储和加载。这个元数据可被写进一个XML映射文件,除了其他东西之外,这个文档还定义了Message类的属性如何映射到MESSAGE表的列。
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class table="Message" name="com.xwj.model.Message">
    <id  name="id" column="message_id">
      <generator class="native"/>
    </id>
    <property name="text" column="message_text"/>
    <many-to-one name="nextMessage" column="next_message_id" foreign-key="fk_next_message"/>
  </class>
</hibernate-mapping>

  3.3存储和加载文件
        
package com.xwj.model;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HelloWorld {

	public static void main(String[] args) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = session.beginTransaction();
		
		Message message = new Message();
		message.setText("hello world");
		session.save(message);
		
		List messages = session.createQuery("from Message m order by m.id asc").list();
		for(Iterator iter=messages.iterator();iter.hasNext();){
		     message = (Message)iter.next();
			System.out.println(message.getText());
		}
		
		transaction.commit();
		session.close();
		HibernateUtil.closeSessionFactory();
	}
}



4. 配置和启动Hibernate
初始化Hibernate的常规方法是从一个Configuration对象中创建一个SessionFactory对象。
4.1 构建SessionFactory
这是一个典型的Hibernate启动过程的例子,在一行代码中,使用自动的配置文件侦查:
sessionFactory = new Configuration().configure().buildSessionFactory();
Hibernate怎么知道配置文件放置的位置,以及要加载那个配置文件呢?
调用new Configuration()时,Hibernate在classpath的根目录下搜索名为hibernate.propertys的文件。如果找到了,所有hibernate.*属性都会被加载并添加到Configuration对象。
调用configure()时,Hibernate在classpath的跟目录下搜索名为Hibernate.cfg.xml的文件,如果无法找到就回抛出一个异常。当然,如果你没有这个配置文件,就不一定要调用这个方法。如果XML配置文件中的设置与较早设置的属性完全相同,XML配置就覆盖前面的设置。
       4.2创建XML配置文件
<!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.url">jdbc:mysql://127.0.0.1:3306/message</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">123456</property>
    	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
   		<property name="hibernate.show_sql">true</property>
    	<property name="hibernate.hbm2ddl.auto">update</property>
    	
    	<property name="hibernate.c3p0.min_size">5</property>
    	<property name="hibernate.c3p0.max_size">20</property>
    	<property name="hibernate.c3p0.timeout">300</property>
    	<property name="hibernate.c3p0.max_statements">50</property>
    	<property name="hibernate.c3p0.idle_test_period">3000</property>
    	
    	<mapping resource="com/xwj/model/Message.hbm.xml"/>
	</session-factory>
</hibernate-configuration>



     4.3数据库连接池
           一般来说,不需要在每次要与数据库交互时都创建连接。反之,java应用程序应该使用连接池(pool)。需要在数据库上工作的每个应用程序线程都从这个池中请求连接,然后当执行完所有SQL操作后把它返回池中。这个池维护着连接,并使打开和关闭连接的成本减到最少。
没有应用程序服务器提供连接池,应用程序要么实现自己的池化算法,要么依赖于第三方的库(如开源C3P0连接池软件)。
    4.4 处理SessionFactory
    在大部分Hibernate应用程序中,SessionFactory应该在应用程序初始化期间被实例化一次。然后单独的实例应该为特定程序中的所有代码所用,任何Session都应该用这个单独的SessionFactory来创建。SessionFactory是线程安全的,且能够被共享;session是个单线程的对象。
package com.xwj.model;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static SessionFactory sessionFactory ;
	static{
		sessionFactory = new Configuration().configure().buildSessionFactory();
	}
	public static SessionFactory getSessionFactory(){
		return sessionFactory;
	}
	public static void closeSessionFactory(){
		getSessionFactory().close();
	}
}



5. 运行应用
在应用程序中运行SchemaExport,生成数据库表。
package com.xwj.model;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class ExportDB {
	public static void  main(String[] args){
		Configuration cfg = new Configuration().configure();
		SchemaExport export =  new SchemaExport(cfg);
		export.create(true, true);
	}
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics