Hibernate入门配置

类别:Java 点击:0 评论:0 推荐:

Hibernate入门配置

一、建表
<<<<<<<<<<<<<表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生成/关闭
<<<<<<<<<<<<<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();

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

}


<<<<<<<<<<<<<测试HbntTestSvlt.java>>>>>>>>>>>>>>>>>>>>>>>

/*
 *
 * @(#)CorpSMS.corpsms V1.0 2005-1-15
 * Copyright 2003 NetEase, Inc. All rights reserved.
 *
 * coder: sweater
 * email: [email protected]
 *
 * 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>

本文地址:http://com.8s8s.com/it/it11872.htm