MyEclipse环境下Hibernate入门实例

来源:互联网 发布:淘宝客推广平台 米粒网 编辑:程序博客网 时间:2024/06/05 04:06

首先在MyEclipse下创建一个WebProject,项目命名为demo,然后【MyEclipse->project capablities->add hibernate capabilities】,跟着向导操作,最后会生成一个hibernate.cfg.xml和一个HibernateSessionFactory.java文件。在向导中要求填写一些数据库连接的配置信息以及HibernateSessionFactory存放的包,配置信息我们可以参考下面的hibernate.cfg.xml来填写,而HibernateSessionFactory我们放在river.hi.demo这个包里面。

1.HibernateSessionFactory.java

package river.hi.demo;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;/** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution.  Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */public class HibernateSessionFactory {    /**      * Location of hibernate.cfg.xml file.     * Location should be on the classpath as Hibernate uses       * #resourceAsStream style lookup for its configuration file.      * The default classpath location of the hibernate config file is      * in the default package. Use #setConfigFile() to update      * the location of the configuration file for the current session.        */    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();    private static org.hibernate.SessionFactory sessionFactory;    private static Configuration configuration = new Configuration();    private static ServiceRegistry serviceRegistry;     static {        try {            configuration.configure();            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();            sessionFactory = configuration.buildSessionFactory(serviceRegistry);        } catch (Exception e) {            System.err.println("%%%% Error Creating SessionFactory %%%%");            e.printStackTrace();        }    }    private HibernateSessionFactory() {    }    /**     * Returns the ThreadLocal Session instance.  Lazy initialize     * the <code>SessionFactory</code> if needed.     *     *  @return Session     *  @throws HibernateException     */    public static Session getSession() throws HibernateException {        Session session = (Session) threadLocal.get();        if (session == null || !session.isOpen()) {            if (sessionFactory == null) {                rebuildSessionFactory();            }            session = (sessionFactory != null) ? sessionFactory.openSession()                    : null;            threadLocal.set(session);        }        return session;    }    /**     *  Rebuild hibernate session factory     *     */    public static void rebuildSessionFactory() {        try {            configuration.configure();            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();            sessionFactory = configuration.buildSessionFactory(serviceRegistry);        } catch (Exception e) {            System.err.println("%%%% Error Creating SessionFactory %%%%");            e.printStackTrace();        }    }    /**     *  Close the single hibernate session instance.     *     *  @throws HibernateException     */    public static void closeSession() throws HibernateException {        Session session = (Session) threadLocal.get();        threadLocal.set(null);        if (session != null) {            session.close();        }    }    /**     *  return session factory     *     */    public static org.hibernate.SessionFactory getSessionFactory() {        return sessionFactory;    }    /**     *  return hibernate configuration     *     */    public static Configuration getConfiguration() {        return configuration;    }}

2.hibernate.cfg.xml(在src目录下)

<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools.                   --><hibernate-configuration><session-factory>    <property name="dialect">        org.hibernate.dialect.SQLServerDialect    </property><!-- 连接字符串 -->    <property name="connection.url">    jdbc:sqlserver://localhost:1433;DataBaseName=BankCreditLoanDB    </property>    <property name="connection.username">sa</property>    <property name="connection.password">123456</property>     <!-- 数据库驱动 -->     <property name="connection.driver_class">        com.microsoft.sqlserver.jdbc.SQLServerDriver     </property>    <property name="myeclipse.connection.profile">    </property>    <!-- 映射文件,是后来添加的,不是想到自动生成的 -->    <mapping resource="Customer.hbm.xml" /></session-factory></hibernate-configuration>

3.创建数据库

--创建数据库BankCreditLoanDBUSE masterGO CREATE DATABASE BankCreditLoanDBGO use BankCreditLoanDBgo--创建客户表T_Customercreate table T_Customer(id int primary key,customer_id varchar(20) not null,customer_name varchar(10) not null,sex varchar(2) not null,adress varchar(30) not null,phone varchar(20) not null,begin_date varchar(10) not null)--输入表T_Customer记录insert T_Customervalues (1001,430682199407218888,'沈圳','女','湖南岳阳','13278894597','2014-07-21')insert T_Customervalues (1002,430682199407219999,'刘超君','男','湖南湘乡','15888889999','2014-07-21')insert T_Customervalues (1003,430682199407217777,'胡伟','男','湖南永州','15888887777','2014-07-21')

4. *.hbm.xml映射文件

我们知道Hibernate是用户将对象与数据库表进行映射,那么下面编写映射文件:Customer.hbm.xml,从代码中我们可以看到name与column属性,name表示Customer类中的属性,column表示数据库表T_Customer中的字段名称。类中的属性和表中的字段可以不相同,如果相同的话column可以省略。

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!-- <hibernate-mapping package="com.demo.hibernate.beans"> --><hibernate-mapping>    <class name="entity.Customer" table="T_Customer">        <id name="id" column="id" >            <generator class="native" />        </id>        <property name="customer_id" />        <property name="customer_name"/>        <property name="sex"/>        <property name="adress"/>        <property name="phone"/>        <property name="begin_date"/>    </class></hibernate-mapping>

5.编写持久化类Customer.java,

这里我们不一定要求Customer类中的属性与表T_Customer的字段相同,不过如果相同则可以省去一些步骤,就是前面提到的*.hbm.xml文件中的一些字段可以省略。

package entity;public class Customer {    private int id;    private String customer_id;    private String customer_name;    private String sex;    private String adress;    private String phone;    private String begin_date;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getCustomer_id() {        return customer_id;    }    public void setCustomer_id(String customer_id) {        this.customer_id = customer_id;    }    public String getCustomer_name() {        return customer_name;    }    public void setCustomer_name(String customer_name) {        this.customer_name = customer_name;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public String getAdress() {        return adress;    }    public void setAdress(String adress) {        this.adress = adress;    }    public String getPhone() {        return phone;    }    public void setPhone(String phone) {        this.phone = phone;    }    public String getBegin_date() {        return begin_date;    }    public void setBegin_date(String begin_date) {        this.begin_date = begin_date;    }}

6.编写DAO类CustomerDAO.java

DAO就是Database Access Objects,数据访问对象的英文缩写。顾名思义对数据库操作的方法都写在这个类中,就比如代码中getCustomer()方法就是需要读取数据库信息。不过hibernate因为通过映射的方法不直接使用SQL语句操纵数据库,而是引入了HQL语言。最明显的一点是:

Query query=session.createQuery(“from Customer where customer_name=?”);

这里from Customer中的Customer是指Customer类而不是Customer表,HQL直接对对象操作。

package river.hi.demo;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import entity.Customer;public class CustomerDAO {    public Customer getCustomer(String customerName) throws HibernateException{        Session session=null;        Transaction tx=null;        Customer c=null;        try        {            session=HibernateSessionFactory.getSession();            tx=session.beginTransaction();            Query query=session.createQuery("from Customer where customer_name=?");            query.setString(0, customerName.trim());            c=(Customer)query.uniqueResult();            query=null;            //session.save(user);            tx.commit();            //session.close();        }        catch(HibernateException e)        {            System.out.println(e.getMessage());            e.printStackTrace();        }        return c;    }}

7.测试

通过客户姓名查询客户地址:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@ page import="river.hi.demo.*" %><%@ page import="entity.*" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>        <%         Customer c = new CustomerDAO().getCustomer("刘超君");        out.println(c.getAdress());        %>  </body></html>
0 0
原创粉丝点击