MyEclipse4.1+hibernate3.05+mySql5.0開發J2EE入門
Posted on 2006-11-09 17:49 semovy 閱讀(639) 評論(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() {
??? }
} <!-- Generated by MyEclipse Hibernate Tools.?????????????????? --> ?<session-factory> ?</session-factory> </hibernate-configuration> ? /** public class Employee? implements java.io.Serializable {
???? /**
??? /** default constructor */ ?/** minimal constructor */ ??? public Integer getId() { ??? public String getName() { import java.util.ArrayList; import org.hibernate.Session; import com.semovy.framework.base.HibernateSession; <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
(3).自動在classes下產生hibernate.cfg.xml配置文件
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
????????? "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
????????? "
<hibernate-configuration>
??<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" /><!--對應對象映射文件資源-->.
三、打開MyEclipse的DB Browser選擇Employee右擊creating hibernate mapping,設置持久類路徑好之后。
便自動產生Employee持久類,與同一目錄下的Employee.hbm.xml兩個文件
1).
package com.semovy.business.pojo;
?* Employee generated by MyEclipse - Hibernate Tools
?*/
??? // Fields???
? *
? */
?private static final long serialVersionUID = 1L;
?private Integer id;
???? private String name;
??? // Constructors
??? public Employee() {
??? }
??? public Employee(Integer id) {
??????? this.id = id;
??? }
???
??? /** full constructor */
??? public Employee(Integer id, String name) {
??????? this.id = id;
??????? this.name = name;
??? }
??? // Property accessors
??????? return this.id;
??? }
???
??? public void setId(Integer id) {
??????? this.id = id;
??? }
??????? 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"
"<!--
??? 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.List;
import org.hibernate.Transaction;
/**
?* 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+"/";
%>
<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>
六、發布應用