用Struts和Hibernate完成簡單的查詢資料庫,顯示類別信息的簡單案例 ...
Struts2學習筆記一結合Hibernate完成查詢商品類別簡單案例(工具IDEA)
2.資料庫準備

1 /* 2 Navicat MySQL Data Transfer 3 4 Source Server : GaGa 5 Source Server Version : 50549 6 Source Host : localhost:3306 7 Source Database : day38hibernate 8 9 Target Server Type : MYSQL 10 Target Server Version : 50549 11 File Encoding : 65001 12 13 Date: 2018-01-26 21:04:36 14 */ 15 16 SET FOREIGN_KEY_CHECKS=0; 17 18 -- ---------------------------- 19 -- Table structure for t_category 20 -- ---------------------------- 21 DROP TABLE IF EXISTS `t_category`; 22 CREATE TABLE `t_category` ( 23 `cid` int(11) NOT NULL AUTO_INCREMENT, 24 `cname` varchar(255) DEFAULT NULL, 25 PRIMARY KEY (`cid`) 26 ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8; 27 28 -- ---------------------------- 29 -- Records of t_category 30 -- ---------------------------- 31 INSERT INTO `t_category` VALUES ('1', '水果'); 32 INSERT INTO `t_category` VALUES ('2', '電子產品'); 33 INSERT INTO `t_category` VALUES ('3', '食物'); 34 35 -- ---------------------------- 36 -- Table structure for t_product 37 -- ---------------------------- 38 DROP TABLE IF EXISTS `t_product`; 39 CREATE TABLE `t_product` ( 40 `pid` int(11) NOT NULL AUTO_INCREMENT, 41 `pname` varchar(255) DEFAULT NULL, 42 `price` double DEFAULT NULL, 43 `cid` int(11) DEFAULT NULL, 44 PRIMARY KEY (`pid`), 45 KEY `FKq8yr5sflwtcj3jqp58x0oy7lx` (`cid`), 46 CONSTRAINT `FKq8yr5sflwtcj3jqp58x0oy7lx` FOREIGN KEY (`cid`) REFERENCES `t_category` (`cid`) 47 ) ENGINE=InnoDB AUTO_INCREMENT=121 DEFAULT CHARSET=utf8; 48 49 -- ---------------------------- 50 -- Records of t_product 51 -- ---------------------------- 52 INSERT INTO `t_product` VALUES ('1', '葡萄', '8', '1'); 53 INSERT INTO `t_product` VALUES ('2', '李子', '4.5', '1'); 54 INSERT INTO `t_product` VALUES ('3', '柚子', '16.8', '1'); 55 INSERT INTO `t_product` VALUES ('4', '櫻桃', '14.8', '1'); 56 INSERT INTO `t_product` VALUES ('5', '橙子', '5.8', '1'); 57 INSERT INTO `t_product` VALUES ('6', '蘋果', '6', '1'); 58 INSERT INTO `t_product` VALUES ('7', '西瓜', '2', '1'); 59 INSERT INTO `t_product` VALUES ('8', '梨子', '3.5', '1'); 60 INSERT INTO `t_product` VALUES ('9', '藍莓', '10', '1'); 61 INSERT INTO `t_product` VALUES ('10', '香蕉', '2', '1'); 62 INSERT INTO `t_product` VALUES ('11', 'iPhone6s', '6500', '2'); 63 INSERT INTO `t_product` VALUES ('12', 'iPhone4s', '3000', '2'); 64 INSERT INTO `t_product` VALUES ('13', 'Mac', '18000', '2'); 65 INSERT INTO `t_product` VALUES ('14', '戰神', '6600', '2'); 66 INSERT INTO `t_product` VALUES ('15', 'iPhone5s', '4300', '2'); 67 INSERT INTO `t_product` VALUES ('16', 'iPhone7', '8000', '2'); 68 INSERT INTO `t_product` VALUES ('17', '拯救者', '8000', '2'); 69 INSERT INTO `t_product` VALUES ('18', 'iPhone6', '5000', '2'); 70 INSERT INTO `t_product` VALUES ('19', 'iPhone5', '3600', '2'); 71 INSERT INTO `t_product` VALUES ('20', 'iPhone4', '2500', '2'); 72 INSERT INTO `t_product` VALUES ('21', '羊肉', '56', '3'); 73 INSERT INTO `t_product` VALUES ('22', '豬肉', '17', '3'); 74 INSERT INTO `t_product` VALUES ('23', '魚', '7', '3'); 75 INSERT INTO `t_product` VALUES ('24', '上海青', '3.5', '3'); 76 INSERT INTO `t_product` VALUES ('25', '牛肉', '22', '3'); 77 INSERT INTO `t_product` VALUES ('26', '白菜', '4', '3'); 78 INSERT INTO `t_product` VALUES ('27', '辣條', '2', '3'); 79 INSERT INTO `t_product` VALUES ('28', '麵包', '6', '3'); 80 INSERT INTO `t_product` VALUES ('29', '雞肉', '8.6', '3'); 81 INSERT INTO `t_product` VALUES ('30', '速食麵', '3.5', '3');資料庫準備
3.配置文件準備
1)Category映射文件配置

1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping> 6 <class name="com.gaga.bean.Category" table="t_category"> 7 <id name="cid" column="cid"> 8 <generator class="native"/> 9 </id> 10 <property name="cname" column="cname"/> 11 12 <!--配置多方(Set) 13 一,通過Set標簽配置多方 14 1.1name屬性: 一方類裡面Set集合的變數名 15 --> 16 <set name="products" fetch="select" lazy="false"> 17 <!--1.2 column: 外鍵的列名 --> 18 <key column="cid"/> 19 <!--1.3 class: 對方類的全限定名 --> 20 <one-to-many class="com.gaga.bean.Product"/> 21 </set> 22 23 </class> 24 </hibernate-mapping>Category映射文件配置
2)Product映射文件配置

1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping> 6 <class name="com.gaga.bean.Product" table="t_product"> 7 <id name="pid" column="pid"> 8 <generator class="native"/> 9 </id> 10 <property name="pname" column="pname"/> 11 <property name="price" column="price"/> 12 13 <!--一, 配置一方 14 name屬性: 多方類裡面一方對象的屬性名 15 class屬性: 一方類的全限定名 16 column屬性: 外鍵的列名 17 --> 18 <many-to-one name="category" class="com.gaga.bean.Category" column="cid" /> 19 20 </class> 21 </hibernate-mapping>Product映射文件配置
4.配置核心文件hebernate.cfg.xml

1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <!--一, 必配(驅動, 資料庫的路徑, 用戶名, 密碼 , 方言) --> 8 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> 9 <property name="hibernate.connection.url">jdbc:mysql:///day38hibernate</property> 10 <property name="hibernate.connection.username">root</property> 11 <property name="hibernate.connection.password">123</property> 12 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 13 14 <!--二, 選配 --> 15 <!--2.1 顯示sql語句 --> 16 <property name="hibernate.show_sql">true</property> 17 <!--2.2 格式化sql --> 18 <property name="hibernate.format_sql">true</property> 19 <!--2.3 配置hibernate自動創建表 --> 20 <property name="hibernate.hbm2ddl.auto">update</property> 21 <!--2.4 集成c3p0 --> 22 <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property> 23 <property name="hibernate.c3p0.max_size">10</property> 24 25 <!--2.6 打開session和本地線程綁定 --> 26 <property name="hibernate.current_session_context_class">thread</property> 27 28 <!--三, 導入映射文件 resource映射文件的路徑 resource屬性就是映射文件的路徑 --> 29 <mapping resource="com/gaga/bean/Category.hbm.xml"/> 30 <mapping resource="com/gaga/bean/Product.hbm.xml"/> 31 32 </session-factory> 33 </hibernate-configuration>核心配置文件
5.Struts2.xml配置

1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <!DOCTYPE struts PUBLIC 4 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 5 "http://struts.apache.org/dtds/struts-2.3.dtd"> 6 7 <struts> 8 <package name="category" extends="struts-default" namespace="/"> 9 <action name="category_*" class="com.gaga.servlet.CategoryAction" method="{1}"> 10 <result name="success">list.jsp</result> 11 <result name="error">msg.jsp</result> 12 </action> 13 </package> 14 15 </struts>Struts2.xml
6.utils導入

package com.gaga.utils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** *作用: *1. 提供session *2. 保證SessionFactory全局只有一個 * */ public class HibernateUtils { private static Configuration configuration = null; private static SessionFactory sessionFactory = null; /** * 保證SessionFactory全局只有一個 */ static{ //1. 創建配置對象, 進行配置 configuration = new Configuration(); configuration.configure(); //2. 構建session工廠(相當於連接池) 內置連接池 ---> c3p0 dbcp 阿裡druid 光連接池 sessionFactory = configuration.buildSessionFactory(); } private HibernateUtils() { } //每次都是獲得的新的session,資料庫操作完成之後需要close public static Session openSession(){ //3. 獲得session (相當於連接) Session session = sessionFactory.openSession(); return session; } //4. 從本地線程獲得Session(前提是你已經在核心配置文件裡面配置了 <property name="hibernate.current_session_context_class">thread</property>) //從本地線程獲得的session(第一次沒有, 獲得新的存到本地線程裡面,下一次直接從本地線程獲得 ), 不需要close public static Session getCurrentSession(){ Session session = sessionFactory.getCurrentSession(); return session; } }View Code
7.編寫Action類

package com.gaga.servlet; import com.gaga.bean.Category; import com.gaga.service.CategoryService; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; import java.util.List; public class CategoryAction { public String findAll() { //1. 獲得請求參數 //2. 調用業務 try { System.out.println("CategoryAction接受了請求"); CategoryService categoryService = new CategoryService(); List<Category> list = categoryService.findAll(); //3. 把list存到域裡面, 轉發頁面 ServletActionContext.getRequest(); HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("list", list); return "success"; } catch (Exception e) { e.printStackTrace(); HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("msg", "錯誤"); return "error"; } } }View Code
8.編寫service層

1 package com.gaga.service; 2 3 import com.gaga.bean.Category; 4 import com.gaga.dao.CategoryDao; 5 6 import java.util.List; 7 8 public class CategoryService { 9 public List<Category> findAll() { 10 CategoryDao categoryDao = new CategoryDao(); 11 12 return categoryDao.findAll(); 13 } 14 }View Code
9.編寫dao層

1 package com.gaga.dao; 2 3 import com.gaga.bean.Category; 4 import com.gaga.utils.HibernateUtils; 5 import org.hibernate.Session; 6 import org.hibernate.Transaction; 7 8 import java.util.List; 9 10 public class CategoryDao { 11 public List<Category> findAll() { 12 Session session = HibernateUtils.getCurrentSession(); 13 Transaction transaction = session.beginTransaction(); 14 List<Category> list = null; 15 16 list = session.createCriteria(Category.class).list(); 17 18 transaction.commit(); 19 20 System.out.println("CategoryDao結果list:---"+list); 21 return list; 22 } 23 }View Code
10.前端jsp頁面佈置

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- saved from url=(0044)http://localhost:8080/day41C_Product/product --> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <style>#BAIDU_DSPUI_FLOWBAR,.adsbygoogle,.ad,div[class^="ad-widsget"],div[id^="div-gpt-ad-"],a[href*="cpro.baidu.com"],a[href*="@"][href*=".exe"],a[href*="/?/"][href*=".exe"],.adpushwin{display:none!important;max-width:0!important;max-height:0!important;overflow:hidden!important;}</style></head> <body> <center> <h1>類別信息</h1> <table border="1px" width="500px" cellspacing="0"> <tbody> <c:forEach items="${list }" var="c"> <tr> <td colspan="3" style="color: red; font-size: 30px">分類名稱:${c.cname }</td > </tr> <tr> <td>商品ID</td> <td>商品名稱</td> <td>商品價格</td> </tr> <c:forEach items="${c.products}" var="p"> <tr> <td>${p.pid }</td> <td>${p.pname }</td> <td>${p.price }</td> </tr> </c:forEach> </c:forEach> </tbody></table> </center> </body></html>View Code
11.發佈到Tomcat,結果顯示