Struts2学习笔记NO.1------结合Hibernate完成查询商品类别简单案例(工具IDEA)

    Struts2学习笔记一结合Hibernate完成查询商品类别简单案例(工具IDEA)

1.jar包准备

Hibernate+Struts2 jar包

struts的jar比较多,可以从Struts官方提供的demo中拿到必要的jar就行. 在apps/struts2-blank项目下

2.数据库准备

 /*
Navicat MySQL Data Transfer Source Server : GaGa
Source Server Version : 50549
Source Host : localhost:3306
Source Database : day38hibernate Target Server Type : MYSQL
Target Server Version : 50549
File Encoding : 65001 Date: 2018-01-26 21:04:36
*/ SET FOREIGN_KEY_CHECKS=0; -- ----------------------------
-- Table structure for t_category
-- ----------------------------
DROP TABLE IF EXISTS `t_category`;
CREATE TABLE `t_category` (
`cid` int(11) NOT NULL AUTO_INCREMENT,
`cname` varchar(255) DEFAULT NULL,
PRIMARY KEY (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of t_category
-- ----------------------------
INSERT INTO `t_category` VALUES ('1', '水果');
INSERT INTO `t_category` VALUES ('2', '电子产品');
INSERT INTO `t_category` VALUES ('3', '食物'); -- ----------------------------
-- Table structure for t_product
-- ----------------------------
DROP TABLE IF EXISTS `t_product`;
CREATE TABLE `t_product` (
`pid` int(11) NOT NULL AUTO_INCREMENT,
`pname` varchar(255) DEFAULT NULL,
`price` double DEFAULT NULL,
`cid` int(11) DEFAULT NULL,
PRIMARY KEY (`pid`),
KEY `FKq8yr5sflwtcj3jqp58x0oy7lx` (`cid`),
CONSTRAINT `FKq8yr5sflwtcj3jqp58x0oy7lx` FOREIGN KEY (`cid`) REFERENCES `t_category` (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=121 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of t_product
-- ----------------------------
INSERT INTO `t_product` VALUES ('1', '葡萄', '8', '1');
INSERT INTO `t_product` VALUES ('2', '李子', '4.5', '1');
INSERT INTO `t_product` VALUES ('3', '柚子', '16.8', '1');
INSERT INTO `t_product` VALUES ('4', '樱桃', '14.8', '1');
INSERT INTO `t_product` VALUES ('5', '橙子', '5.8', '1');
INSERT INTO `t_product` VALUES ('6', '苹果', '6', '1');
INSERT INTO `t_product` VALUES ('7', '西瓜', '2', '1');
INSERT INTO `t_product` VALUES ('8', '梨子', '3.5', '1');
INSERT INTO `t_product` VALUES ('9', '蓝莓', '10', '1');
INSERT INTO `t_product` VALUES ('10', '香蕉', '2', '1');
INSERT INTO `t_product` VALUES ('11', 'iPhone6s', '6500', '2');
INSERT INTO `t_product` VALUES ('12', 'iPhone4s', '3000', '2');
INSERT INTO `t_product` VALUES ('13', 'Mac', '18000', '2');
INSERT INTO `t_product` VALUES ('14', '战神', '6600', '2');
INSERT INTO `t_product` VALUES ('15', 'iPhone5s', '4300', '2');
INSERT INTO `t_product` VALUES ('16', 'iPhone7', '8000', '2');
INSERT INTO `t_product` VALUES ('17', '拯救者', '8000', '2');
INSERT INTO `t_product` VALUES ('18', 'iPhone6', '5000', '2');
INSERT INTO `t_product` VALUES ('19', 'iPhone5', '3600', '2');
INSERT INTO `t_product` VALUES ('20', 'iPhone4', '2500', '2');
INSERT INTO `t_product` VALUES ('21', '羊肉', '56', '3');
INSERT INTO `t_product` VALUES ('22', '猪肉', '17', '3');
INSERT INTO `t_product` VALUES ('23', '鱼', '7', '3');
INSERT INTO `t_product` VALUES ('24', '上海青', '3.5', '3');
INSERT INTO `t_product` VALUES ('25', '牛肉', '22', '3');
INSERT INTO `t_product` VALUES ('26', '白菜', '4', '3');
INSERT INTO `t_product` VALUES ('27', '辣条', '2', '3');
INSERT INTO `t_product` VALUES ('28', '面包', '6', '3');
INSERT INTO `t_product` VALUES ('29', '鸡肉', '8.6', '3');
INSERT INTO `t_product` VALUES ('30', '方便面', '3.5', '3');

数据库准备

3.配置文件准备

  1)Category映射文件配置

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.gaga.bean.Category" table="t_category">
<id name="cid" column="cid">
<generator class="native"/>
</id>
<property name="cname" column="cname"/> <!--配置多方(Set)
一,通过Set标签配置多方
1.1name属性: 一方类里面Set集合的变量名
-->
<set name="products" fetch="select" lazy="false">
<!--1.2 column: 外键的列名 -->
<key column="cid"/>
<!--1.3 class: 对方类的全限定名 -->
<one-to-many class="com.gaga.bean.Product"/>
</set> </class>
</hibernate-mapping>

Category映射文件配置

  2)Product映射文件配置

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.gaga.bean.Product" table="t_product">
<id name="pid" column="pid">
<generator class="native"/>
</id>
<property name="pname" column="pname"/>
<property name="price" column="price"/> <!--一, 配置一方
name属性: 多方类里面一方对象的属性名
class属性: 一方类的全限定名
column属性: 外键的列名
-->
<many-to-one name="category" class="com.gaga.bean.Category" column="cid" /> </class>
</hibernate-mapping>

Product映射文件配置

4.配置核心文件hebernate.cfg.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--一, 必配(驱动, 数据库的路径, 用户名, 密码 , 方言) -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///day38hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!--二, 选配 -->
<!--2.1 显示sql语句 -->
<property name="hibernate.show_sql">true</property>
<!--2.2 格式化sql -->
<property name="hibernate.format_sql">true</property>
<!--2.3 配置hibernate自动创建表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--2.4 集成c3p0 -->
<property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.max_size">10</property> <!--2.6 打开session和本地线程绑定 -->
<property name="hibernate.current_session_context_class">thread</property> <!--三, 导入映射文件 resource映射文件的路径 resource属性就是映射文件的路径 -->
<mapping resource="com/gaga/bean/Category.hbm.xml"/>
<mapping resource="com/gaga/bean/Product.hbm.xml"/> </session-factory>
</hibernate-configuration>

核心配置文件

5.Struts2.xml配置

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

 <!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"> <struts>
<package name="category" extends="struts-default" namespace="/">
<action name="category_*" class="com.gaga.servlet.CategoryAction" method="{1}">
<result name="success">list.jsp</result>
<result name="error">msg.jsp</result>
</action>
</package> </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;
} }

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";
}
}
}

8.编写service层

 package com.gaga.service;

 import com.gaga.bean.Category;
import com.gaga.dao.CategoryDao; import java.util.List; public class CategoryService {
public List<Category> findAll() {
CategoryDao categoryDao = new CategoryDao(); return categoryDao.findAll();
}
}

9.编写dao层

 package com.gaga.dao;

 import com.gaga.bean.Category;
import com.gaga.utils.HibernateUtils;
import org.hibernate.Session;
import org.hibernate.Transaction; import java.util.List; public class CategoryDao {
public List<Category> findAll() {
Session session = HibernateUtils.getCurrentSession();
Transaction transaction = session.beginTransaction();
List<Category> list = null; list = session.createCriteria(Category.class).list(); transaction.commit(); System.out.println("CategoryDao结果list:---"+list);
return list;
}
}

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>

11.发布到Tomcat,结果显示

Struts2学习笔记NO.1------结合Hibernate完成查询商品类别简单案例(工具IDEA)

上一篇:struts2学习笔记之四:多配置文件支持和常用配置参数


下一篇:[IDEA_2] IDEA 问题合集