iT邦幫忙

DAY 11
5

JSP 學習分享系列 第 11

JSP 和 Hibernate 的設定教學第二篇

介紹Mapping Config和如何使用Hibernate 新增一筆資料
1.使用NetBeans的精靈建立一個UserData.hbm.xml
裡面主要在Mapping資料庫和UserData.java裡的參數

	<?xml version="1.0" encoding="UTF-8"?>

<hibernate-mapping>
  <class name="demo.UserData" table="userdata">
    <id name="userid" column="UserID" />
    <property column="UserName" name="username"/>
    <property column="UserPassword" name="userpassword"/>
  </class>
</hibernate-mapping>

2.一個簡單的輸入三個欄位的畫面
=== insUserData.jsp ===

	<%@page contentType="text/html" pageEncoding="UTF-8"%>

    
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert UserData</title>
    
    
      <form name="recvud" action="recvUserData.jsp" method="POST">
        User ID :<input type="text" name="userid" value="" size="20" /><br>
        User PWD:<input type="password" name="userpwd" value="" size="30" /><br>
        User Name:<input type="text" name="username" value="" size="50" /><br>
        <input type="submit" value="Save" name="save" />
      </form>
    

3.使用Hibernate存到資料庫後秀成功或失敗
=== recvUserData.jsp ===

  <%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="demo.*" %>
<%
  boolean insrs = false;
  org.hibernate.Session sess = null;
  org.hibernate.SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
  sess = sessionFactory.openSession();
  try {
    org.hibernate.Transaction tx = sess.beginTransaction();
    UserData ud = new UserData();
    String uid = request.getParameter("userid");
    String upwd = request.getParameter("userpwd");
    String uname = request.getParameter("username");
    ud.setUserid(uid);
    ud.setUsername(uname);
    ud.setUserpassword(upwd);
    sess.save(ud);
    try {
      tx.commit();
      insrs = true;
    } catch (org.hibernate.TransactionException hix) {
      System.out.println("Something went wrong!"+hix);
    }
  } catch (Exception ex) {
    System.out.println(ex);
  } finally {
    sess.flush();
    sess.close();
  }
%>

  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Inser To DataBase</title>
  
  

    <%
      if(insrs){
    %><font color="green" size="10">Insert To DataBase  Success!</font><%
      }else{
    %><font color="red" size="10">Insert To DataBase  Error!</font><%
      }
    %>
  

上一篇
JSP 和 Hibernate 的設定教學第一篇
下一篇
JSP 和 Hibernate 的設定教學第三篇
系列文
JSP 學習分享30

尚未有邦友留言

立即登入留言