`
bestxiaok
  • 浏览: 455783 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

hibernate入门配置

    博客分类:
  • SSH
阅读更多
HibernateUtil.java
package com.netease.wireless.groupsms.hbnt.util;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.cfg.Configuration;
/**
 * 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 HibernateUtil {
    /** 
     * Location of hibernate.cfg.xml file.
     * NOTICE: Location should be on the classpath as Hibernate uses
     * #resourceAsStream style lookup for its configuration file. That
     * is place the config file in a Java package - the default location
     * is the default Java package.<br><br>
     * Examples: <br>
     * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml". 
     * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code> 
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";//hibernate.cfg.xml
    /** Holds a single instance of Session */
    private static final ThreadLocal threadLocal = new ThreadLocal();
    /** The single instance of hibernate configuration */
    private static final Configuration cfg = new Configuration();
    /** The single instance of hibernate SessionFactory */
    private static net.sf.hibernate.SessionFactory sessionFactory;
    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session currentSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
   &nbsp;    if (session == null) {
            if (sessionFactory == null) {
                try {
                    cfg.configure(CONFIG_FILE_LOCATION);
                    //cfg.configure();
                    sessionFactory = cfg.buildSessionFactory();
                }
                catch (Exception e) {
                    System.err.println("%%%% Error Creating SessionFactory %%%%");
                    System.err.println("|||||||||||||" + e.getMessage());
                    e.printStackTrace();
                }
            }
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }
        return session;
    }
    /**
     *  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();
        }
    }
    /**
     * Default constructor.
     */
    private HibernateUtil() {
    }
}

 一.建表

 

cat表

CREATE TABLE cat (
    cat_id varchar(20) NOT NULL,
    NAME varchar(20) NOT NULL,
    sex CHAR(1),
    weight FLOAT,
    PRIMARY KEY (cat_id)
);

 

二、po层(系统以cat.hbm.xml为准,一个xml可以写多个class)

<<<<<<<<<<<<<cat.hbm.xml>>>>>>>>>>>>>>>>>>>>>>>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
    <class name="com.netease.wireless.groupsms.hbnt.po.Cat" table="cat">
        <id name="id" type="string" unsaved-value="null" >
            <column name="cat_id" sql-type="varchar(20)" not-null="true"/>
            <generator class="uuid.hex"/>
        </id>
        <property name="name">
            <column name="NAME" sql-type="varchar(20)" not-null="true"/>
        </property>
        <property name="sex"/>
        <property name="weight"/>
    </class>
</hibernate-mapping>

 

<<<<<<<<<<<<<Cat.java>>>>>>>>>>>>>>>>>>>>>>>>>
package com.netease.wireless.groupsms.hbnt.po;
public class Cat {
    private String id;
    private String name;
    private char sex;
    private float weight;
    public Cat() {
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public char getSex() {
        return sex;
    }
    public void setSex(char sex) {
        this.sex = sex;
    }
    public float getWeight() {
        return weight;
    }
    public void setWeight(float weight) {
        this.weight = weight;
    }
    public String toString() {
        String strCat = new StringBuffer()
            .append(this.getId()).append(", ")
            .append(this.getName()).append(", ")
            .append(this.getSex()).append(", ")
            .append(this.getWeight())
            .toString();
        return strCat;
    }
}

 三、hibernate.cfg.xml
(切切不要自己去加属性,基本的就两个connection.datasource和dialect)

<property name="connection.username">root</property>       
<property name="connection.password">root</property>
<property name="connection.provider_class">net.sf.hibernate.connection.DatasourceConnectionProvider</property>
<property name="jndi.class">org.gjt.mm.mysql.Driver</property>
<<<<<<<<<<<<<hibernate.cfg.xml>>>>>>>>>>>>>>>>>>>>>>>
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 2.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<!-- DO NOT EDIT: This is a generated file that is synchronized -->
<!-- by MyEclipse Hibernate tool integration.                   -->
<hibernate-configuration>
    <session-factory>
        <!-- properties -->
        <property name="connection.datasource">java:comp/env/jdbc/test</property>
        <property name="show_sql">true</property>
        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
     
        <!-- mapping files -->
  <mapping resource="com/netease/wireless/groupsms/hbnt/po/cat.hbm.xml"/>
  
    </session-factory>
</hibernate-configuration>

 四、测试servlet
//Session生成/关闭

<<<<<<<<<<<<<测试HbntTestSvlt.java>>>>>>>>>>>>>>>>>>>>>>>
/*
 * 
 * @(#)CorpSMS.corpsms V1.0 2005-1-15
 * Copyright 2003 NetEase, Inc. All rights reserved.
 * 
 * coder: sweater 
 * email: wtshi@corp.netease.com
 * 
 * graphic designer:
 * email:
 *
 * fuction:向电话薄中添加组和电话号码
 * 
 */
package com.netease.wireless.groupsms.vo;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import com.netease.wireless.groupsms.hbnt.po.Cat;
import com.netease.wireless.groupsms.hbnt.util.HibernateUtil;
/**
 *
 * @author sweater
 */
public class HbntTestSvlt extends HttpServlet {
    /**
     * Constructor of the object.
     */
    public HbntTestSvlt() {
        super();
    }
    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }
    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
     out.println("<title>Hello Hibernate</title>");
        out.println("</head>");
        out.println("<body>");
     out.println("Hello Hibernate!<br>");
        try {
            Session session = HibernateUtil.currentSession();
            Transaction tx = session.beginTransaction();
            Query query = session.createQuery("select cat from Cat as cat where cat.sex = :sex");
            query.setCharacter("sex", 'F');
            for (Iterator it = query.iterate(); it.hasNext();) {
                Cat cat = (Cat) it.next();
                out.println("Cat: " + cat.toString() + "<br>");
            }
            tx.commit();
            HibernateUtil.closeSession();
        } catch (HibernateException e) {
            System.out.println(e.getMessage());
            //System.out.println(e.printStackTrace());
        }
        out.println("</body>");
        out.println("</html>");
    }
    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.print("    This is ");
        out.print(this.getClass());
        out.println(", using the POST method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }
    /**
     * Returns information about the servlet, such as 
     * author, version, and copyright. 
     *
     * @return String information about this servlet
     */
    public String getServletInfo() {
        return "This is my default servlet created by Eclipse";
    }
    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occure
     */
    public void init() throws ServletException {
        // Put your code here
    }
}

 

<<<<<<<<<<<<<该servlet使用时的web.xml>>>>>>>>>>>>>>>>>>>>>>>
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
 xmlns="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>hbnttest</description>
    <display-name>hbnttest</display-name>
    <servlet-name>HbntTestSvlt</servlet-name>
    <servlet-class>com.netease.wireless.groupsms.vo.HbntTestSvlt</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>HbntTestSvlt</servlet-name>
    <url-pattern>/servlet/HbntTestSvlt</url-pattern>
  </servlet-mapping>
</web-app>
</SPAN< p>

 

分享到:
评论

相关推荐

    完整Hibernate入门配置示例

    Hibernate3.3.1,MySQL5.1.36 独立的Java Application源程序,完整的Hibernate3.3.1入门级(配置)完整示例. 未用Eclipse或MyEclipse,JC几乎纯手工实现,含所需库文件. 2009-12-15

    Hibernate入门到精通

    "Hibernate入门到精通" Hibernate 是一个基于Java的ORM(Object-Relational Mapping,对象关系映射)框架,它提供了一种简洁高效的方式来访问和操作关系数据库。下面是 Hibernate 的主要知识点: Hibernate 简介 ...

    Hibernate入门jar包

    本压缩包提供的是Hibernate入门所需的jar包,包括了Hibernate的核心库以及与之配合使用的相关组件。让我们深入探讨一下这些jar包以及它们在Hibernate中的作用。 1. Hibernate核心库: - `hibernate-core.jar`:这...

    Hibernate入门案例源码

    【Hibernate入门案例源码】是针对初学者设计的一份教程,旨在帮助理解并掌握Java持久化框架Hibernate的基础应用。Hibernate是一个强大的ORM(对象关系映射)框架,它简化了数据库与Java对象之间的交互,使开发者可以...

    初学hibernate,hibernate入门

    **初学Hibernate,Hibernate入门** Hibernate是一个开源的对象关系映射(ORM)框架,它为Java开发者提供了方便的数据持久化服务。在Java应用中,通过Hibernate,开发者可以将数据库操作抽象成对象模型,使得代码...

    Hibernate入门

    ### Hibernate入门知识点详解 #### Hibernate概述与ORM思想 - **定义**:Hibernate是一个开源的、轻量级的对象关系映射(Object-Relational Mapping,简称ORM)框架,它主要应用于JavaEE架构中的DAO(Data Access ...

    Hibernate入门(代码+笔记)

    **Hibernate入门** Hibernate是一款强大的Java持久化框架,它简化了数据库与Java对象之间的交互,使得开发者无需编写大量的SQL语句,就能实现数据的增删改查。本教程将分为五个部分,逐步深入Hibernate的世界。 **...

    Hibernate入门 - 基础配置

    【Hibernate入门 - 基础配置】 在Java开发中,Hibernate是一个非常重要的对象关系映射(ORM)框架,它极大地简化了数据库操作。本文将深入介绍Hibernate的基础配置和功能,帮助初学者快速入门。 一、ORM框架与...

    hibernate入门小例子

    【hibernate入门小例子】是一个适合初学者的教程,主要涵盖了如何在JavaWeb项目中使用Hibernate框架与MySQL数据库进行集成。在这个例子中,我们将会深入理解Hibernate的核心概念,包括实体映射、对象关系映射(ORM)...

    Hibernate入门到精通.pdf

    《Hibernate入门到精通》这本书是针对Java开发人员深入学习Hibernate框架的一份宝贵资源。Hibernate是一个开源的对象关系映射(ORM)框架,它极大地简化了Java应用程序与数据库之间的交互。通过使用Hibernate,...

    hibernate入门--第一个实例

    在这个“hibernate入门--第一个实例”中,我们将了解如何设置Hibernate环境,创建实体类,配置映射文件,以及执行基本的CRUD(创建、读取、更新和删除)操作。 1. **环境搭建** - **下载与安装**: 首先,你需要从...

    hibernate入门

    **hibernate入门** Hibernate 是一个强大的Java持久化框架,它简化了数据库操作,使得开发者无需直接编写SQL语句即可实现对象与关系数据库之间的映射。这个文档将带你步入Hibernate的世界,了解其基本概念和核心...

    Hibernate入门教程.pdf

    ### Hibernate入门教程知识点详解 #### 一、Hibernate框架简介 **Hibernate** 是一款开放源代码的**对象关系映射(Object-Relational Mapping,简称ORM)**框架,它为Java应用提供了一种高效的机制,用于处理Java...

    Hibernate入门笔记

    ### Hibernate入门知识点详解 #### 一、环境搭建与配置 - **工程创建**:首先,创建一个名为`HibernateDemo`的Java工程,这是构建Hibernate应用的基础。为了使工程能够识别和运行Hibernate相关的代码,需要正确地...

    Hibernate入门(配置文件+增删改查)

    在这个“Hibernate入门”教程中,我们将深入探讨Hibernate的基本概念、配置文件以及如何进行增删改查操作。 首先,Hibernate的核心是其配置文件(通常命名为`hibernate.cfg.xml`),这是连接数据库的关键。配置文件...

    Hibernate入门 - 基础配置详细说明

    本文将深入探讨Hibernate入门时的基础配置,帮助初学者更好地理解和使用该框架。 首先,Hibernate 配置文件有两种形式:`hibernate.properties` 和 `hibernate.cfg.xml`。尽管两者都可以用于定义配置,但在处理`hbm...

    hibernate入门实例操作步骤

    本篇将详细介绍Hibernate入门实例的操作步骤,包括手工配置文件和利用Eclipse自动生成配置的两种方法。 **一、手工配置文件** 1. **环境准备** 在开始前,确保已安装JDK、Eclipse IDE,并在项目中引入Hibernate的...

    hibernate入门教程

    Hibernate的入门学习主要包括理解这些基本概念和操作,后续深入学习则会涉及到复杂映射、事务处理、性能优化和缓存管理等高级话题。随着不断实践和学习,开发者可以充分利用Hibernate框架提供的各种特性,编写更加...

    MyEclipse Hibernate 快速入门中文版

    总结而言,《MyEclipse Hibernate 快速入门中文版》是一份全面的学习资料,涵盖了从环境配置到实际操作的全过程,适合想要快速上手Hibernate和MyEclipse集成的开发者。通过学习,你将能够熟练地在MyEclipse中使用...

Global site tag (gtag.js) - Google Analytics