1.创建Web项目HS_test如图所示:

 

 

2.创建数据库DBHSTest,在数据库中创建表Teacher,并插入数据

 

3.在Myeclipse中调出DB Brower视图

右键->New:

  

连接后如图所示:

 

4.导入Hibernate

右击项目->myeclipse->Add Hibernate Capabilities:

 选择Hibernate3.3  点击Next:

默认设置,在src文件夹下创建hibernate.cfg.xml文件,点击Next:

 

选择之前新建的DB Driver:DBHSTest,配置自动显示出来,点击Next:

 

将 HibernateSessionFactory类建立在com.miaomiao.hs.test包下,点击Finish,完成导入。

 查看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="dialect">org.hibernate.dialect.SQLServerDialect</property>
        <property name="connection.url">jdbc:sqlserver://127.0.0.1:1433;databaseName=dbHSTest</property>
        <property name="connection.username">sa</property>
        <property name="connection.password">123</property>
        <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
        <property name="myeclipse.connection.profile">dbHSTest</property>
    
    </session-factory>

</hibernate-configuration>

5.创建ORM映射 反向工程

(1)选择DB Brower 下的dbHSTest ->...->dbo->table->Teacher,右键,选择Hibernate ReverseEngineering:

 

如图选择,点击Next,全部默认设置

 创建完成后,生成如图Java文件和xml文件:

Teacher.hbm.xml文件内容

<?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">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.miaoshi.hs.orm.Teacher" table="Teacher" schema="dbo" catalog="dbHSTest">
        <id name="id" type="java.lang.String">
            <column name="ID" length="10" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="Name" length="20" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

  Teacher.java文件内容:

package com.miaoshi.hs.orm;

/**
 * Teacher entity. @author MyEclipse Persistence Tools
 */

public class Teacher implements java.io.Serializable {

    // Fields

    private String id;
    private String name;

    // Constructors

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

    /** full constructor */
    public Teacher(String id, String name) {
        this.id = id;
        this.name = name;
    }

    // Property accessors

    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

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

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

}

6.实现对数据库的增删改查

(1)显示教师信息

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.miaoshi.hs.orm.Teacher"%>
<%@page import="com.miaoshi.hs.HibernateSessionFactory"%>
<%@page import="org.hibernate.Session"%>
<%@page import="org.hibernate.Query"%>
<%
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 'TeacherList.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>
    <%
        Session ss = HibernateSessionFactory.getSession();
        ss.beginTransaction();
        
        Query query = ss.createQuery("from Teacher");
        List<Teacher> teachers = query.list();
        
        ss.getTransaction().commit();
        ss.close();
        
     %>
     <center>
    教师列表<br><br>
    <a href="TeacherAdd.html">添加</a>
        <table border="1" cellspacing="0" cellpadding="4">
            <tr>
                <th>工号</th>
                <th>姓名</th>
                <th>操作</th>
            </tr>
            <% for(int i = 0;i<teachers.size();i++){ %>
            <tr>
                <td><%=teachers.get(i).getId() %></td>
                <td><%=teachers.get(i).getName() %></td>
                <td><a href="StudentEdit.jsp?ID=<%=teachers.get(i).getId()%>">编辑</a>
                <a href="servlet/StudentDelete.do?ID=<%=teachers.get(i).getId()%>">删除</a></td>
            </tr>
            <%} %>
        </table>
    </center>
  </body>
</html>

(2)增加教师信息

TeacherAdd.html

<!DOCTYPE html>
<html>
  <head>
    <title>TeacherAdd.html</title>
    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>
  
  <body>
    <form id="form1" name="form1" method="post"
        action="/servlet/TeacherAdd">
        <center>
            添加教师信息<br> <br> 工号<input type="text" id="ID" name="ID"><br>
            <br> 姓名<input type="text" id="Name" name="Name"><br>
            <br> <input type="submit" value="确定">
        </center>
    </form>
  </body>
</html>

创建TeacherAdd的Servlet

package com.miaoshi.hs;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import com.miaoshi.hs.HibernateSessionFactory;
import com.miaoshi.hs.orm.Teacher;

public class TeacherAdd extends HttpServlet {

    /**
     * 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("<!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 GET method");
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    /**
     * 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 {

        request.setCharacterEncoding("UTF-8");
        String strID = "";
        String strName = "";
        
        strID = request.getParameter("ID");
        strName = request.getParameter("Name");
        Session session =  HibernateSessionFactory.getSession();
        try{
            
            session.beginTransaction();
            
            Teacher student = new Teacher();
            student.setId(strID);
            student.setName(strName);
            session.save(student);
            
            session.getTransaction().commit();
            session.close();
            
            response.sendRedirect("../TeacherList.jsp");
            
        }
        catch(Exception e){
            session.clear();
            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>Add fail</TITLE></HEAD>");
            out.println("  <BODY>");
            out.print("    add fail! ");
            out.println("  <a href='../TeacherList.jsp'>return</a>");
            out.println(e.getMessage());
            //out.print(this.getClass());
            out.println("  </BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    }

}

未完待续。。。

 

posted on 2018-05-03 20:26  曹婷婷  阅读(354)  评论(0编辑  收藏  举报