eclipse学习(第二章:初识ssh)——24.struts整合hibernate
- 前言
- 项目jar包下载位置
- 项目初始化及jar包情况
- 创建一个名为student的数据库并生成一个简单的student表
- 创建Student
- 创建StudentDAO
- 创建AddStudentAction
- 修改web.xml
- 创建struts.xml
- 创建student.jsp
- 创建hibernate.cfg.xml
- 测试
- 中途遇到的异常
- 1、java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.Environment
- 2、Caused by: org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [/hibernate.cfg.xml]
- 3、Caused by: java.sql.SQLException: No timezone mapping entry for 'UTC;characterEncoding=UTF-8'
- 项目地址
前言
本文是参考自https://www.w3cschool.cn/struts_2/struts_hibernate.html做的一个日志记录
项目jar包下载位置
struts相关jar包请到该网站下载,下载一个all版本吧
https://struts.apache.org/download.cgi
hibernate4及以上的jar包http://hibernate.org/orm/releases/
hibernate3的相关jar包下载地址
https://sourceforge.net/projects/hibernate/files/hibernate3/
在这里还有一些其他jar包下载的位置介绍
https://blog.youkuaiyun.com/qq3892997/article/details/78473375
当然如果你实在找不到的情况下可以去maven仓库中找一下。不过推荐直接去找不同的框架下载,因为他们一般都是组合好的了,自己组合容易出问题。
项目初始化及jar包情况
我之前其实整合高版本成功了,但是由于中途出现了一个错误,我不确定是不是版本问题导致我跑去找hibernate3的版本了。hibernate相关jar包拉取需要去找到lib包下面的required文件夹内的全部jar包,如果有jpa的包也需要加入,如果解压后打开有个hibernate3的包也要拉进去,这个是核心包,后面版本会变成hibernate-core放进去required里面的。
至于struts的jar包正常拉取就行了,还有一个是联系包struts2-dojo-plugin-2.3.37.jar
如果你想要深入了解一下jar包是干嘛的可以看看这篇
https://blog.youkuaiyun.com/yanwushu/article/details/7570431
创建一个名为student的数据库并生成一个简单的student表
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`subject` varchar(40) NOT NULL,
`score` double(11,0) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', '张三', '语文', '60');
INSERT INTO `student` VALUES ('2', '李四', '数学', '90');
INSERT INTO `student` VALUES ('3', '王五', '英语', '80');
创建Student
Student,这里主要是创建一些属性跟设置的数据库里面的对应上
package com.czx.hibernate.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "student")
public class Student {
public Double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
@Id
@GeneratedValue
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "subject")
private String subject;
@Column(name = "score")
private Double score;
}
创建StudentDAO
StudentDAO,这里主要是进行数据库操作的。
package com.czx.hibernate.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.czx.hibernate.pojo.Student;
import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
public class StudentDAO {
@SessionTarget
Session session;
@TransactionTarget
Transaction transaction;
@SuppressWarnings("unchecked")
public List<Student> getStudentList(){
List<Student> studentList = new ArrayList<Student>();
try {
studentList = session.createQuery("from Student").list();
}catch(Exception e){
e.printStackTrace();
}
return studentList;
}
public void addStudent(Student student) {
session.save(student);
}
}
创建AddStudentAction
AddStudentAction,这里通过调用dao里面的方法来实现添加学生和展示学生列表
package com.czx.hibernate.action;
import java.util.ArrayList;
import java.util.List;
import com.czx.hibernate.dao.StudentDAO;
import com.czx.hibernate.pojo.Student;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class AddStudentAction extends ActionSupport implements ModelDriven<Student>{
Student student = new Student();
List<Student> studentList = new ArrayList<Student>();
StudentDAO studentDAO = new StudentDAO();
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public List<Student> getStudentList() {
return studentList;
}
public void setStudentList(List<Student> studentList) {
this.studentList = studentList;
}
@Override
public Student getModel() {
// TODO Auto-generated method stub
return student;
}
@Override
public String execute() throws Exception {
studentDAO.addStudent(student);
return "success";
}
public String listStudent() {
studentList = studentDAO.getStudentList();
return "success";
}
}
修改web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ssh_learn_hibernate_integration</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
创建struts.xml
这里的话设置了一下,我返回的不是一个页面而是另一个action,要设置一下结果类型。
<?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>
<constant name="struts.devMode" value="true"></constant>
<package name="student" extends="hibernate-default">
<action name="addStudent" class="com.czx.hibernate.action.AddStudentAction" method="execute">
<result name="success" type="redirect">listStudent</result>
</action>
<action name="listStudent" class="com.czx.hibernate.action.AddStudentAction" method="listStudent">
<result name="success">student.jsp</result>
</action>
</package>
</struts>
创建student.jsp
student.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:form action="addStudent" method="post">
<s:textfield label="名称" name="name"></s:textfield>
<s:textfield label="科目" name="subject"></s:textfield>
<s:textfield label="分数" name="score"></s:textfield>
<s:submit label="提交"></s:submit>
</s:form>
<table>
<tr>
<td>名称</td>
<td>科目</td>
<td>分数</td>
</tr>
<s:iterator value="studentList">
<tr>
<td><s:property value="name"/></td>
<td><s:property value="subject"/></td>
<td><s:property value="score"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>
创建hibernate.cfg.xml
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- mysql的驱动包 -->
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- 数据库连接地址,这里数据库以参数形式传入,以;分隔不同参数 -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/student?serverTimezone=UTC
</property>
<!-- 数据库账号 -->
<property name="hibernate.connection.username">
root
</property>
<!-- 数据库密码 -->
<property name="hibernate.connection.password">
root
</property>
<!-- 数据库连接池 -->
<property name="hibernate.connection.pool_size">
10
</property>
<!-- 日志文件中是否展示sql -->
<property name="hibernate.show_sql">
true
</property>
<!-- 设置Hibernate SQL方言 -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- 其实这个hibernate.hbm2ddl.auto参数的作用主要用于:自动创建|更新|验证数据库表结构。如果不是此方面的需求建议set value="none"。 -->
<!-- create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。 -->
<!-- create-drop : 每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。-->
<!-- update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。 -->
<!-- validate : 每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。-->
<property name="hibernate.hbm2ddl.auto">
update
</property>
<mapping class="com.czx.hibernate.pojo.Student"/>
</session-factory>
</hibernate-configuration>
测试
访问http://localhost:8080/ssh_learn_hibernate_integration/student.jsp
一开始空空荡荡的。然后我们这里试着输一下内容,名称为“chen”,科目为“数学”,分数为“90.5”,然后点击submit看看。
结果如下你会看到我们新增的内容能够完美展示出来了。同时url也会发生改变哦,如果你直接访问这个地址也能得到这个结果http://localhost:8080/ssh_learn_hibernate_integration/listStudent
中途遇到的异常
中间遇到的异常太多选几个来说吧
1、java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.cfg.Environment
后来发现是hibernate.cfg.xml里面内容写少了,补上就好了。
但凡是那种noclass的你看一下内容有没有缺少jar包和其他就好了。你如果没弄好那么他会报很多缺类noclass异常。
2、Caused by: org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [/hibernate.cfg.xml]
我的问题在于把hibernate.cfg.xml文件放置在某个包中了,hibernate.cfg.xml文件需要放置在src目录下。
3、Caused by: java.sql.SQLException: No timezone mapping entry for ‘UTC;characterEncoding=UTF-8’
我猜测是这个版本过低应该不太支持使用多参数,所以我放弃了加太多参数强行解成功的,如果要使用的话请使用高版本,低版本仅用于学习。
项目地址
这个仓库里面的ssh_learn_hibernate_integration
https://gitee.com/mrchen13427566118/ssh_learn.git
如果不会怎么弄到eclipse的话,就看这里
https://blog.youkuaiyun.com/weixin_43987277/article/details/116936221