springmvc,spring,hibernate5.0整合

目录

    • 1. pom依赖
    • 2. web.xml
    • 3. spring核心配置文件
      • 3.1 jdbc配置信息
      • 3.2 sping 配置文件
    • 4. 实体映射
    • 5. 项目结构
      • 5.1 curd
      • 5.2 页面
    • 6. 测试

1. spring版本 5.1.5 RELEASE
2. hibernate版本 5.3.9.Final
3. 数据源使用c3p0

项目使用eclipse2017 + maven构建, 完成学生的新增,查询功能。学生表是根据hibernate对实体类进行映射生成的。

1. pom依赖

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>cn.bitqian</groupId><artifactId>springmvc02</artifactId><version>0.0.1-SNAPSHOT</version><packaging>war</packaging><name>springmvc02 Maven Webapp</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target></properties><dependencies><!-- servlet --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version></dependency> <!-- mvc --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.1.5.RELEASE</version></dependency><!-- 整合包 --><!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --><dependency><groupId>org.springframework</groupId>  <artifactId>spring-orm</artifactId><version>5.1.6.RELEASE</version></dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.1.5.RELEASE</version></dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.2</version><scope>runtime</scope></dependency><!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.2</version></dependency><!-- hibernate --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>5.3.9.Final</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.20</version></dependency><!-- junit --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency>  </dependencies><build><finalName>springmvc02</finalName><pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --><plugins><plugin><artifactId>maven-clean-plugin</artifactId><version>3.1.0</version></plugin><!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --><plugin><artifactId>maven-resources-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.22.1</version></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>3.2.2</version></plugin><plugin><artifactId>maven-install-plugin</artifactId><version>2.5.2</version></plugin><plugin><artifactId>maven-deploy-plugin</artifactId><version>2.8.2</version></plugin></plugins></pluginManagement></build>
</project>

2. web.xml

注意xml的头文件,版本,2.3的头文件有坑low,这里用的是3.0版本。

ioc容器加载。mvc核心控制器的创建。

<?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>Archetype Created Web Application</display-name><!-- 启动项目时加载容器 --><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>

3. spring核心配置文件

3.1 jdbc配置信息

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssh_study?serverTimezone=GMT
jdbc.username=root
password=123456

3.2 sping 配置文件

hibernate 使用了注解的方式,没有配置映射文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 开启mvc注解驱动 --><mvc:annotation-driven /><context:component-scan base-package="cn.bitqian.**" /><!-- 加载jdbc配置文件 --><context:property-placeholder location="classpath:jdbc.properties"/><!-- c3p0数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${driver}"></property><property name="jdbcUrl" value="${url}"></property><property name="user" value="${jdbc.username}"></property><property name="password" value="${password}"></property></bean><!-- session 工厂 --><bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><!-- hibernate 相关配置 --><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop><!-- 根据实体类反转表 --><prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop><prop key="hibernate.format_sql">true</prop></props></property><!-- hibernate映射文件 注解扫描 --><property name="packagesToScan" value="cn/bitqian/entity"></property></bean><!-- hibernate模板来操作数据库 --><bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 事务 --><bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- xml事务配置 --><tx:advice id="advice" transaction-manager="transactionManager"><tx:attributes><!-- 对下面的符合规则方法进行事务控制 --><tx:method name="save*" propagation="REQUIRED"/><tx:method name="add*" propagation="REQUIRED"/><tx:method name="insert*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="delete*" propagation="REQUIRED"/><!-- 只读 --><tx:method name="*" read-only="true" propagation="SUPPORTS"/></tx:attributes></tx:advice><aop:config><!-- 切点 --><aop:pointcut expression="execution(* cn.bitqian.service.impl.*.*(..))" id="pointcut"/><!-- 事务顾问 --><aop:advisor advice-ref="advice" pointcut-ref="pointcut"/></aop:config><!-- 开启事务注解驱动 --><tx:annotation-driven transaction-manager="transactionManager"/></beans>

4. 实体映射

package cn.bitqian.entity;import java.io.Serializable;
import java.util.Date;import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;import org.springframework.format.annotation.DateTimeFormat;/*** * @author echo lovely* @time 2020/11/4**/
@Entity(name="StudentInfo")
@Table(name="student_info")
public class StudentInfo implements Serializable {private static final long serialVersionUID = -5075710692395281523L;@Id@GeneratedValue(strategy=GenerationType.AUTO) // 主键自增// @Column(name="stu_id")private Integer stuId;@Column(name="stu_name")// 列名private String stuName;@Column(name="stu_gender")private Integer stuGender;@Column(name="stu_birth")@DateTimeFormat(pattern="yyyy-MM-dd") // mvc将字符串转换日期private Date stuBirth;// 此字段会被忽悠,不会被反转@Transientprivate String abc;public StudentInfo() {}public Integer getStuId() {return stuId;}public void setStuId(Integer stuId) {this.stuId = stuId;}public String getStuName() {return stuName;}public void setStuName(String stuName) {this.stuName = stuName;}public Integer getStuGender() {return stuGender;}public void setStuGender(Integer stuGender) {this.stuGender = stuGender;}public Date getStuBirth() {return stuBirth;}public void setStuBirth(Date stuBirth) {this.stuBirth = stuBirth;}}

5. 项目结构

5.1 curd

dao

package cn.bitqian.dao.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;import cn.bitqian.dao.StudentInfoDao;
import cn.bitqian.entity.StudentInfo;@Repository
public class StudentInfoDaoImpl implements StudentInfoDao {@Autowiredprivate HibernateTemplate ht;@Overridepublic List<StudentInfo> queryAll() {// 查询所有// return  (List<StudentInfo>) ht.find("from StudentInfo");return ht.loadAll(StudentInfo.class);}@Overridepublic void add(StudentInfo stu) {// 新增ht.save(stu);}}

service(省略),没有业务

package cn.bitqian.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import cn.bitqian.dao.StudentInfoDao;
import cn.bitqian.entity.StudentInfo;
import cn.bitqian.service.StudentInfoService;@Service
public class StudentInfoServiceImpl implements StudentInfoService {@Autowiredprivate StudentInfoDao stuDao;@Overridepublic List<StudentInfo> queryAll() throws Exception {List<StudentInfo> list = null;try {list = stuDao.queryAll();} catch (Exception e) {// 捕捉到异常并抛出e.printStackTrace();throw new Exception(e);}return list;}@Overridepublic void add(StudentInfo stu) throws Exception {try {stuDao.add(stu);} catch (Exception e) {e.printStackTrace();throw new Exception(e);}}/*** 测试为事务注解*/@Transactional@Overridepublic void testAdd1(StudentInfo stu) {stuDao.add(stu);}}

controller

package cn.bitqian.controller;import javax.annotation.Resource;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;import cn.bitqian.entity.StudentInfo;
import cn.bitqian.service.StudentInfoService;@Controller
@RequestMapping("/stu")
public class StudentInfoController {@Resource()private StudentInfoService stuInfoService;@GetMapping("/list")public ModelAndView queryAllStu() {ModelAndView mv = new ModelAndView();try {// 带上查询的数据mv.addObject("stuList", stuInfoService.queryAll());} catch (Exception e) {e.printStackTrace();mv.addObject("msg", "出错拉");}mv.setViewName("/list.jsp");return mv;}@PostMapping("/add")public ModelAndView saveStu(StudentInfo stuInfo) {stuInfoService.testAdd1(stuInfo);// 查询一遍return this.queryAllStu();}}

5.2 页面

  1. 新增
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增学生</title>
</head>
<body><form action="stu/add" method="post"><input type="text" name="stuName"/> <br/><input type="radio" name="stuGender" value="0"/><input type="radio" name="stuGender" value="1"/><br/><input type="date" name="stuBirth"/> <br/><input type="submit" value="add"/> <br/></form></body>
</html>
  1. 查询
    坑:jstl,识别不了。。可能我导入的servlet(4.0)版本太高,而头文件的版本当时是2.3… 把头文件改为3.0就行了
无法在web.xml或使用此应用程序部署的jar文件中解析绝对uri:[http://java.sun.com
<%@ page language="java" isELIgnored="false" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生查询</title>
</head>
<body><table><tr><td>id</td><td>name</td><td>gender</td><td>birth</td></tr><c:forEach items="${stuList}" var="stu"><tr><td>${stu.stuId}</td><td>${stu.stuName}</td><td>${stu.stuGender == 0 ? "男" : "女"}</td><td>${stu.stuBirth} </td></tr></c:forEach></table></body>
</html>

6. 测试



本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/420546.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MYSQL 查看表上索引的 1 方法

前期准备&#xff1a; create table T9(A int ,B text,C text,fulltext index fix_test_for_T8_B(B));#在定义表的时候加索引 create unique index ix_test_for_T8_A on T9(A);#加朴素索引 create fulltext index fix_test_for_T8_C on T9(C);#加全文索引 --------------------…

springmvc 结合ajax批量新增

目录1. 需要注意的问题2. 页面代码3. controller定义参数接收1. 需要注意的问题 mvc框架的处理日期问题ResponseBody响应对象是自定义对象&#xff0c;响应不是jsonResopnseBody响应自定义对象时&#xff0c;日期为是long类型的数结束数据方法的参数&#xff0c;该如何定义&am…

手写简单的启动器

starter1. target2. 手写启动器~2.1 自动装配&#xff0c;自定义属性2.2 启动器&#xff0c;引用自动装配模块3. 在自己的项目引用上面的starter1. target 1. 启动器只用来做依赖导入(导入配置模块)2. 专门来写一个自动配置模块3. 启动器依赖自动配置&#xff1b;别人只需要引入…

Android 颜色渲染(九) PorterDuff及Xfermode详解

Android 颜色渲染(九) PorterDuff及Xfermode详解之前已经讲过了除ComposeShader之外Shader的全部子类, 在讲ComposeShader(组合渲染)之前, 由于构造ComposeShader需要 PorterDuffXfermode或者PorterDuff.Mode作为参数,所以在此先详细地了解下这两个类的作用,这对之后的绘图会…

每次新建Android项目都报样式找不到的错误?

问题描述如图再网上找了下说改为<style name"AppBaseTheme" parent"android:Theme.Light">这样就行了的确改为这样就ok了但是如果每次都要这么改&#xff0c;不是很烦&#xff1f;有没有彻底解决这个问题的方法&#xff1f;谢谢 解决方案1新建的时候…

Qt多线程学习:创建多线程

【为什么要用多线程&#xff1f;】 传统的图形用户界面应用程序都仅仅有一个运行线程&#xff0c;而且一次仅仅运行一个操作。假设用户从用户界面中调用一个比較耗时的操作&#xff0c;当该操作正在运行时&#xff0c;用户界面一般会冻结而不再响应。这个问题能够用事件处理和多…

图解springmvc 执行流程

核心对象 DispatcherServlet 核心控制器负责请求&#xff0c;响应&#xff0c;数据的分发。HandlerMapping 处理器映射器&#xff0c;负责到controller中&#xff0c;找到对应的方法&#xff0c;返回给核心控制器。HandleAdapter 处理适配器&#xff0c;将handle找到的方法执行…

VMware下Windows Server 2012添加新磁盘

系统管理员在VM下新装了一台Windows Server 2012服务器&#xff0c;我在上面安装了SQL Server 2014 Standard版数据库&#xff0c;安装之初&#xff0c;只分配了一个C盘&#xff0c;我想在这台服务器上添加了三个磁盘&#xff08;虚拟磁盘&#xff09;&#xff0c;步骤如下截图…

mybatis Caused by: java.io.IOException: Could not find resource xxx.xml

翻译&#xff1a;找不到mybatis的映射配置文件。。。 配置文件名别写错了… <!-- 扫描mapper --> <mappers><!-- src/main/resources下 使用\ --><!-- <mapper resource"cn\bitqian\mapper\ordersMapper.xml"/> --><!-- src/mai…

mybatis新增返回主键值

mapper <?xml version"1.0" encoding"UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace"cn.bitqian.dao.OrdersMa…

测试===JUnit单元测试

测试一&#xff0c;测试分类二&#xff0c;单元测试Junit&#xff0c;你以为的junit只是Test注解吗&#xff0c;shallow..优点&#xff1a;规范&#xff1a;断言&#xff1a;案例demo&#xff1a;junit test case测试类创建&#xff0c;执行测试&#xff0c;结果反馈junit test…

iOS IAP教程

1. 创建应用首先进入iTunes Connect然后按下 Manage Your Applications接下来按下Add New Applicationbutton创建应用2. 在应用中创建IAP创建应用之后&#xff0c;在Manage Your Applications中点应用的图示&#xff0c;进入应用就会看到上图画面点击Manage In App Purchases就…

mybatis-plus 使用乐观锁修改

title乐观锁与悲观锁解决方案code测试乐观锁与悲观锁 乐观锁&#xff1a;十分乐观&#xff0c;总是认为不会出现问题&#xff0c;无论干什么&#xff0c;都不会去上锁。如果出现了问题&#xff0c;就再次更新值测试。 悲观锁&#xff1a;十分悲观&#xff0c;认为总是出现问题…

EasyUI 在aspx页面显示高度不正常解决办法

<body class"easyui-layout"><form id"form1" runat"server"><table id"dg" class"easyui-datagrid"></table></form> </body> </html>这样写的时候&#xff0c;datagrid显示就不…