Hibernate3入门之第七章sh练习

2024-03-05 08:58

本文主要是介绍Hibernate3入门之第七章sh练习,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Struts2和Hibernate的小练习

  • 简介:查询所有客户信息,并提供删除(Hibernate级联删除)和异步加载查看订单详情的功能。(其他功能可自行添加)

  • 创建 一个web项目,(记得添加struts2过滤器否则struts2框架将不起作用)

  • 导入相应jar包,Struts2,Hibernate以及json所需要的jar包

    Struts2的在struts-2.3.33\apps\struts2-blank.war在WEB-INF\lib下的所有

    Hibernate开发包:

    1. hibernate3.jar

    2. lib/jpa/.jar

    3. lib/required/*.jar

    4. mysql驱动

    5. c3p0

在这里插入图片描述

  • 引入配置文件:

    • struts.xml
    • hibernate.cfg.xml
    • log4j.properties
  • 创建包结构

在这里插入图片描述

  • 工具类代码,获取session对象(配置好实体类和映射文件直接运行生成数据库表)

    public class Hibernate3Utils {private static Configuration configuration;private static SessionFactory sessionFactory;static {configuration = new Configuration().configure();sessionFactory = configuration.buildSessionFactory();}public static SessionFactory getSessionFactory() {return sessionFactory;}public static Session openSession() {return sessionFactory.getCurrentSession();}public static void main(String[] args) {openSession();}
    }
    
  • 创建实体类,使用实体类帮助创建数据库(前提是已经创建好数据库)

    Customer.java

    	private Integer cid;private String cname;private Integer age;private Set<Order> orders;
    

    Order.java

    	private Integer oid;private String addr;private Customer customer;
  • 配置映射

    Customer.hbm.xml

    <hibernate-mapping><class name="com.syj.vo.Customer" table="customer"><id name="cid" column="cid"><generator class="native" /></id><property name="cname"  column="canme"  length="20" /><property name="age" column="age"  /><set name="orders"  cascade="save-update,delete" ><key column="cno"   /><one-to-many class="com.syj.vo.Order" /></set></class>
    </hibernate-mapping>
    

    Order.hbm.xml

    <hibernate-mapping><class name="com.syj.vo.Order" table="orders"><id name="oid"  column="oid"><generator class="native" /></id><property name="addr" column="addr" length="60" /><many-to-one name="customer" class="com.syj.vo.Customer" column="cno"/></class>
    </hibernate-mapping>
    
  • Hibernate配置文件hibernate.cfg.xml(并引入映射)

    hibernate.cfg.xml

    <hibernate-configuration><session-factory name=""><!-- 必须的配置 --><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql:///sh_day04</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">root</property><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><!-- 可选的配置 --><property name="hibernate.show_sql">true</property><!-- 格式化SQL --><property name="hibernate.format_sql">true</property><property name="hibernate.connection.autocommit">false</property><!-- 事务的隔离级别 --><property name="hibernate.connection.isolation">4</property><property name="hibernate.current_session_context_class">thread</property><!-- hbm:映射 to DDL: create drop alter create	 :每次执行的时候,创建一个新的表.(如果以前有该表,将该表删除重新创建.) 一般测试的时候的使用.
    create-drop:每次执行的时候,创建一个新的表,程序执行结束后将这个表,删除掉了.	一般测试的时候使用.
    update	 :如果数据库中没有表,创建一个新的表,如果有了,直接使用这个表.可以更新表的结构.
    validate   :会使用原有的表.完成校验.校验映射文件与表中配置的字段是否一致.不一致报错.
    --><property name="hibernate.hbm2ddl.auto">update</property><!-- 将session对象保存到当前线程中 C3P0连接池设定--><property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property><!--在连接池中可用的数据库连接的最少数目 --><property name="c3p0.min_size">5</property><!--在连接池中所有数据库连接的最大数目  --><property name="c3p0.max_size">20</property><!--设定数据库连接的过期时间,以秒为单位,如果连接池中的某个数据库连接处于空闲状态的时间超过了timeout时间,就会从连接池中清除 --><property name="c3p0.timeout">120</property><!--每3000秒检查所有连接池中的空闲连接 以秒为单位--><property name="c3p0.idle_test_period">3000</property><!-- 通知Hibernate加载那些映射文件-->  <mapping resource="com/syj/vo/Customer.hbm.xml"/><mapping resource="com/syj/vo/Order.hbm.xml"/></session-factory>
    </hibernate-configuration>
    
  • 查询所有客户信息(直接访问action实现,bingzaijsp页面显示)

    web层的查询所有

    	// web层的查询所有public String findAll() {CustomerService customerService = new CustomerService();list = customerService.findAll();return "findAll_sunccess";}
    

    service直接调用

    Dao层进行数据库交互,实现查询

    public List<Customer> findAll() {Session session = Hibernate3Utils.openSession();Transaction ts = session.beginTransaction();List<Customer> list = session.createQuery("from Customer").list();ts.commit();return list;}
    

    struts.xml转跳到listCustomer.jsp

    <package name="default" extends="struts-default" namespace="/"><action name="customer_*" class="com.syj.action.CustomerAction" method="{1}"><result name="findAll_sunccess">listCustomer.jsp</result>	</action>
    </package>
    

    listCustomer.jsp

    <body><h1 align="center">展示所有客户信息</h1><table border="1" width="600" align="center"><tr><th>序号</th><th>姓名</th><th>年龄</th><th>订单详情</th><th>删除</th></tr><s:iterator value="list" status="status"><tr><td align="center"><s:property value="#status.count" /></td><td align="center"><s:property value="cname" /></td><td align="center"><s:property value="age" /></td><td align="center"><!--异步加载时使用--><input  id="but<s:property value="cid"/>" type="button" "showDetail(<s:property value="cid"/>)" value="订单详情"><table border="1" id="tab<s:property value="cid"/>" width="100%"></table></td><td align="center"><ahref="${pageContext.request.contextPath}/customer_delete?cid=<s:property value="cid"/>">删除</a></td></tr></s:iterator></table>
    

在这里插入图片描述

  • 删除客户信息

    点击右侧超链接删除客户信息

    链接转跳,携带id

    href="${pageContext.request.contextPath}/customer_delete?cid=<s:property value="cid"/>">删除</a>
    

    Dao层删除数据库信息

    public void delete(Customer customer) {Session session = Hibernate3Utils.openSession();Transaction ts = session.beginTransaction();Customer c1 = (Customer) session.get(Customer.class, customer.getCid());session.delete(c1);ts.commit();}
    

    struts.xml文件配置(删除完成之后跳转到查询所有客户信息处)

    <result name="delete_sunccess"  type="redirectAction">customer_findAll</result>
    
  • 异步加载展示订单详

在这里插入图片描述

在订单详情处给给按钮添加点击功能(使其异步加载展示个人订单信息)(json的jar包)

<td align="center"><input  id="but<s:property value="cid"/>" type="button" onclick="showDetail(<s:property value="cid"/>)" value="订单详情"><table border="1" id="tab<s:property value="cid"/>" width="100%"></table>
</td>

编写ajax代码

<script type="text/javascript">function showDetail(cid) {var but = document.getElementById("but"+cid);var tab = document.getElementById("tab"+cid);if(but.value == "订单详情"){// 1.创建异步对象:var xhr = createXMLHttpRequest();// 2.设置监听:xhr.onreadystatechange = function(){if(xhr.readyState == 4){if(xhr.status == 200){// alert(xhr.responseText);var data = xhr.responseText;//得到的是一个字符串 // eval函数var json = eval("("+data+")");//将字符串转化成json格式for(var i = 0 ;i<json.length;i++){tab.innerHTML += "<tr><td>"+json[i].oid+"</td><td>"+json[i].addr+"</td></tr>";}}}}// 3.打开连接:xhr.open("GET","${pageContext.request.contextPath}/order_findByCid.action?"+new Date().getTime()+"&cid="+cid,true);// 4.发送:xhr.send(null);but.value = "关闭"; } else {but.value = "订单详情";tab.innerHTML="";}}function createXMLHttpRequest() {var xmlHttp;try { // Firefox, Opera 8.0+, SafarixmlHttp = new XMLHttpRequest(); } catch (e) {try {// Internet ExplorerxmlHttp = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {}}}return xmlHttp;}
</script>

创建一orderAction处理订单详情

OrderAction.java

public class OrderAction extends ActionSupport {private Integer cid;public void setCid(Integer cid) {this.cid = cid;}public String findByCid() throws IOException {OrderService orderService = new OrderService();List<Order> list = orderService.findByCid(cid);// 转jsonJsonConfig jsonConfig = new JsonConfig();jsonConfig.setExcludes(new String[] { "customer" });JSONArray jsonArray = JSONArray.fromObject(list, jsonConfig);ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");ServletActionContext.getResponse().getWriter().println(jsonArray.toString());return NONE;}}

service转接到Dao层

Dao层与数据库进行交互查询订单详情

public List<Order> findByCid(Integer cid) {Session session = Hibernate3Utils.openSession();Transaction tx = session.beginTransaction();Query query = session.createQuery("from Order o where o.customer.cid = ?");// Query query = session.createQuery("from Order o where o.customer = ?");query.setParameter(0, cid);List<Order> list = query.list();tx.commit();return list;}

配置struts.xml文件,订单详情直接异步加载,OrderAction.java返回NONE;

这篇关于Hibernate3入门之第七章sh练习的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/775960

相关文章

从入门到精通详解Python虚拟环境完全指南

《从入门到精通详解Python虚拟环境完全指南》Python虚拟环境是一个独立的Python运行环境,它允许你为不同的项目创建隔离的Python环境,下面小编就来和大家详细介绍一下吧... 目录什么是python虚拟环境一、使用venv创建和管理虚拟环境1.1 创建虚拟环境1.2 激活虚拟环境1.3 验证虚

Java List 使用举例(从入门到精通)

《JavaList使用举例(从入门到精通)》本文系统讲解JavaList,涵盖基础概念、核心特性、常用实现(如ArrayList、LinkedList)及性能对比,介绍创建、操作、遍历方法,结合实... 目录一、List 基础概念1.1 什么是 List?1.2 List 的核心特性1.3 List 家族成

c++日志库log4cplus快速入门小结

《c++日志库log4cplus快速入门小结》文章浏览阅读1.1w次,点赞9次,收藏44次。本文介绍Log4cplus,一种适用于C++的线程安全日志记录API,提供灵活的日志管理和配置控制。文章涵盖... 目录简介日志等级配置文件使用关于初始化使用示例总结参考资料简介log4j 用于Java,log4c

史上最全MybatisPlus从入门到精通

《史上最全MybatisPlus从入门到精通》MyBatis-Plus是MyBatis增强工具,简化开发并提升效率,支持自动映射表名/字段与实体类,提供条件构造器、多种查询方式(等值/范围/模糊/分页... 目录1.简介2.基础篇2.1.通用mapper接口操作2.2.通用service接口操作3.进阶篇3

Python自定义异常的全面指南(入门到实践)

《Python自定义异常的全面指南(入门到实践)》想象你正在开发一个银行系统,用户转账时余额不足,如果直接抛出ValueError,调用方很难区分是金额格式错误还是余额不足,这正是Python自定义异... 目录引言:为什么需要自定义异常一、异常基础:先搞懂python的异常体系1.1 异常是什么?1.2

Python实现Word转PDF全攻略(从入门到实战)

《Python实现Word转PDF全攻略(从入门到实战)》在数字化办公场景中,Word文档的跨平台兼容性始终是个难题,而PDF格式凭借所见即所得的特性,已成为文档分发和归档的标准格式,下面小编就来和大... 目录一、为什么需要python处理Word转PDF?二、主流转换方案对比三、五套实战方案详解方案1:

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Spring Boot 与微服务入门实战详细总结

《SpringBoot与微服务入门实战详细总结》本文讲解SpringBoot框架的核心特性如快速构建、自动配置、零XML与微服务架构的定义、演进及优缺点,涵盖开发环境准备和HelloWorld实战... 目录一、Spring Boot 核心概述二、微服务架构详解1. 微服务的定义与演进2. 微服务的优缺点三

从入门到精通详解LangChain加载HTML内容的全攻略

《从入门到精通详解LangChain加载HTML内容的全攻略》这篇文章主要为大家详细介绍了如何用LangChain优雅地处理HTML内容,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录引言:当大语言模型遇见html一、HTML加载器为什么需要专门的HTML加载器核心加载器对比表二

从入门到进阶讲解Python自动化Playwright实战指南

《从入门到进阶讲解Python自动化Playwright实战指南》Playwright是针对Python语言的纯自动化工具,它可以通过单个API自动执行Chromium,Firefox和WebKit... 目录Playwright 简介核心优势安装步骤观点与案例结合Playwright 核心功能从零开始学习