posts - 0, comments - 77, trackbacks - 0, articles - 356
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

MyEclipse4.1+hibernate3.05+mySql5.0开发J2EE入门

Posted on 2006-11-09 17:49 semovy 阅读(629) 评论(0)  编辑  收藏 所属分类: Hibernate

一、在MySql5.0中建数据库Test与Employee表
create database Test;
use Test;
create table employee
(
      id int(11) primary key not null ,
      name varcahr(50) not null
);
二、
1、在MyEclipse4.1中新建Web-Project 名为myWeb.
2、选择MyEclipse选项的Add Hibernate Capabilities,以使web应用具有hibernate性能,
在配置对话框的最下面的选项应选择Copy checked Library Jars to project floder and add to build-path.
这样项目就添加了HibernateSessionFactory的类,与及hibernate的core jar包和在classes下的hibernate.cfg.xml。
(1)hibernate 核心jar包应该包含:
hibernate3.jar
ehcache-1.1.jar
,antlr-2.7.5H3.jar
asm.jar
jta.jar
commons-logging-1.0.4.jar
asm-attrs.jar

(2).HibernateSessionFactory系统自动类产生的,不可继承的,其方法是静态的,直接使用,不用实例化。

package com.semovy.framework.base;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@linkhttp://hibernate.org/42.html}.
 */
public class HibernateSessionFactory{

    /**
     * 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";

    /** 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 org.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 || !session.isOpen()) {
   if (sessionFactory == null) {
    try {
     cfg.configure(CONFIG_FILE_LOCATION);
     sessionFactory = cfg.buildSessionFactory();
    } catch (Exception e) {
     System.err
       .println("%%%% Error Creating SessionFactory %%%%");
     e.printStackTrace();
    }
   }
   session = (sessionFactory != null) ? sessionFactory.openSession()
     : null;
   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 HibernateSession() {
    }

}
(3).自动在classes下产生hibernate.cfg.xml配置文件
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

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

 <session-factory>
  <property name="connection.username">root</property>
  <property name="connection.url">jdbc:mysql://localhost:3306/test?useUnicode=true;characterEncoding=gbk</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="myeclipse.connection.profile">MySqlDB</property>
  <property name="connection.password">1234</property>
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <mapping resource="com/semovy/business/pojo/Employee.hbm.xml" /><!--对应对象映射文件资源-->.

 </session-factory>

</hibernate-configuration>
三、打开MyEclipse的DB Browser选择Employee右击creating hibernate mapping,设置持久类路径好之后。
便自动产生Employee持久类,与同一目录下的Employee.hbm.xml两个文件

1).
package com.semovy.business.pojo;

 

/**
 * Employee generated by MyEclipse - Hibernate Tools
 */

public class Employee  implements java.io.Serializable {


    // Fields   

     /**
  *
  */
 private static final long serialVersionUID = 1L;
 private Integer id;
     private String name;


    // Constructors

    /** default constructor */
    public Employee() {
    }

 /** minimal constructor */
    public Employee(Integer id) {
        this.id = id;
    }
   
    /** full constructor */
    public Employee(Integer id, String name) {
        this.id = id;
        this.name = name;
    }
    // Property accessors

    public Integer getId() {
        return this.id;
    }
   
    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }
   
    public void setName(String name) {
        this.name = name;
    }
}

2).Employee.hbm.xml文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
    <class name="com.semovy.business.pojo.Employee" table="employee" ><!---一定弃掉catalog属性,我是卡在这里好久,运行有异常-->
        <id name="id" type="integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="name" length="50" />
        </property>
    </class>
</hibernate-mapping>

四,建立Employee持久化类的业务逻辑:
package com.semovy.business.service;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.semovy.framework.base.HibernateSession;
/**
 * this class supply all type of busniss service method for Employees
 * @author Semovy
 * @since 2006-11-08
 * @version 1.0
 */
public class EmployeeService {
 Session session = null;
 public EmployeeService(){}
 public List findAllEmployees()
 {
  List employees = new ArrayList();
  try
  {
   session = HibernateSession.currentSession();
   Transaction tx = session.beginTransaction();
   employees = session.createQuery("from Employee").list();
   tx.commit();
   return employees;
  }
  catch(Exception ex)
  {
   ex.printStackTrace();
   return null;
  }
  finally
  {
   HibernateSession.closeSession();
  }
 }
}
五,建立jsp页面listEmployees.jsp来调用测试hibernate.

<%@ page language="java" import="java.util.*,
com.semovy.business.pojo.Employee,com.semovy.business.service.EmployeeService"
pageEncoding="UTF-8"%>
<%
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 'listEmployees.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>
    This is my JSP page.<br>
    <%
 
    EmployeeService es = new EmployeeService();
    List l = es.findAllEmployees();
    if(l != null)
    {
     Iterator it = l.iterator();
     while(it.hasNext())
     {
      Employee em = (Employee)it.next();
      out.print("ID: " + em.getId() + "Name: " + em.getName()+"<br>");
      
     } 
    }
    %>
  </body>
</html>
六、发布应用


只有注册用户登录后才能发表评论。


网站导航: