hibernate配置,开发过程

来源:互联网 发布:淘宝退货太多会怎么样 编辑:程序博客网 时间:2024/04/30 03:15

首先在hibernate官网下载hibernate压缩包,http://hibernate.org/orm/downloads/,目前版本为4.3.5。下

载后解压缩,将lib文件夹中的required文件夹下的所有jar包加入到项目中(通过buildpath->user library)

hibernate的作用是将我们对对象的操作通过hibernate内部映射成对数据库的操作。

首先建个modelEvent

package main.java.org.hibernate.tutorial.domain;

 

import java.util.Date;

 

public class Event {

    private Long id;

 

    private String title;

    private Date date;

 

    public Event() {}

 

    public Long getId() {

        return id;

    }

 

    private void setId(Long id) {

        this.id = id;

    }

 

    public Date getDate() {

        return date;

    }

 

    public void setDate(Date date) {

        this.date = date;

    }

 

    public String getTitle() {

        return title;

    }

 

    public void setTitle(String title) {

        this.title = title;

    }

}

因为一个model类要对应到数据库的某张表,我们就需要让hibernate知道这个类对应着哪张表,这个用一个xml文件或者注解的方法来说明,这里给出xml的形式,建个Event.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

        "-//Hibernate/HibernateMapping DTD 3.0//EN"

        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

        <hibernate-mappingpackage="main.java.org.hibernate.tutorial.domain">

 

    <class name="Event"table="EVENTS">

        <id name="id"column="EVENT_ID">

            <generatorclass="native"/>

        </id>

        <propertyname="date" type="timestamp"column="EVENT_DATE"/>

        <propertyname="title"/>

    </class>

 

</hibernate-mapping>

 

现在类和表的对应关系确定了,但是连接的数据库的用户名,密码等信息还未确定,我们还需要把建立的对应关系告诉hibernate,同样,hibernate还是使用xml文件的方式来,建立一个全局xml文件hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

          "-//Hibernate/HibernateConfiguration DTD 3.0//EN"

          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

 

<!-- Generated by MyEclipse Hibernate Tools.                   -->

<hibernate-configuration>

 

    <session-factory>

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

        <propertyname="connection.url">jdbc:mysql://localhost:3306/zhangmeng</property>

        <propertyname="connection.username">zhangmeng</property>

        <propertyname="connection.password">q476914133</property>

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

        <propertyname="myeclipse.connection.profile">zhangmeng</property>

        

        <!-- JDBC connectionpool (use the built-in) -->

        <propertyname="connection.pool_size">1</property>

 

        <!-- Enable Hibernate'sautomatic session context management -->

        <propertyname="current_session_context_class">thread</property>

 

        <!-- Disable thesecond-level cache  -->

        <propertyname="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

 

        <!-- Echo all executedSQL to stdout -->

        <propertyname="show_sql">true</property>

 

        <!-- Drop and re-createthe database schema on startup -->

        <propertyname="hbm2ddl.auto">update</property>

        <propertyname="javax.persistence.validation.mode">none</property> 

 

        <mappingresource="main/java/org/hibernate/tutorial/domain/Event.hbm.xml"/>

    

    </session-factory>

 

</hibernate-configuration>

这里配置了连接数据库的url,用户名,密码等信息,还声明了建立的对应关系。这样我们就通过这个配置文件知道了怎样连接数据库,有哪些对应关系。

现在基本框架就形成了。使用hibernate,我们只需要告诉hibernate我们要做什么,然后hibernate就自动的在内部根据我们的配置文件去进行操作,怎样操作完全在hibernate内部实现。

接下来就需要我们告诉hibernate我们要做什么,这需要是哪个对象:configurationsessionfactorysession。他们的功能在这儿不再说明,这儿只说明他们如何取得。

package main.java.org.hibernate.tutorial.util;

 

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 SessionFactorybuildSessionFactory() {

        try {

            //Create the SessionFactory from hibernate.cfg.xml

         Configurationconfiguration = new Configuration().configure();

         ServiceRegistryserviceRegistry = newStandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

         SessionFactorysessionFactory = configuration.buildSessionFactory(serviceRegistry);

         returnsessionFactory;

        }

        catch (Throwable ex) {

            //Make sure you log the exception, as it might be swallowed

            System.err.println("InitialSessionFactory creation failed." + ex);

            thrownew ExceptionInInitializerError(ex);

        }

    }

 

    public static SessionFactory getSessionFactory() {

        return sessionFactory;

    }

 

}

使用单例模式,注意hibernate4hibernate3获取sessionfactoy的方法不同。

建立一个测试类:

package main.java.org.hibernate.tutorial;

 

import org.hibernate.Session;

 

import java.util.*;

 

import   main.java.org.hibernate.tutorial.domain.Event;

import  main.java.org.hibernate.tutorial.util.HibernateUtil;

 

public class EnentManger {

 

    public static void main(String[] args) {

        EnentManger mgr = newEnentManger();

 

        

            mgr.createAndStoreEvent("MyEvent", new Date());

       

 

        HibernateUtil.getSessionFactory().close();

    }

 

    private void createAndStoreEvent(String title,Date theDate) {

        Session session =HibernateUtil.getSessionFactory().getCurrentSession();

        session.beginTransaction();

 

        Event theEvent = newEvent();

        theEvent.setTitle(title);

        theEvent.setDate(theDate);

        session.save(theEvent);

 

        session.getTransaction().commit();

    }

 

}

通过先前的配置,和获取到的三个对象,当我们使用session.save(theEvent);就相当于告诉hibernate我们要将theEvent对象中的数据insert到对应的表中,hibernate内部就会根据我们的配置信息,连接到数据库,找到表,将数据插入,内部实现完全自动,我们所做的事就是告诉hibernate去做这件事。

 

 

这就是hibernate的初始完整的配置,开发过程。

 

0 0
原创粉丝点击