Spring+SpringMVC+Spring Data JPA完美整合
使用Maven实现SSS框架的整合。
方便记录,专门建了一个pom项目用来整合SSS框架所用的jar包
1、POM项目,作为父级项目,记录整个整合中的依赖jar包
pom文件
<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>org.qf</groupId>
<artifactId>M_SSS_Pom</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<description>这是SSS整合框架的所有依赖</description>
<!--Spring+SpringMVC+SpringDataJPA+Hibernate JPA -->
<dependencies>
<!--Spring+Spring Data -->
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.3.RELEASE</version>
</dependency>
<!--SpringMVC -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<!--数据库连接池,Hibernate -->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- 数据库连接驱动 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<!--构建信息 -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
2、创建整合的war项目继承刚刚创建的POM项目
pom文件:
<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>
<parent>
<groupId>org.qf</groupId>
<artifactId>M_SSS_Pom</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>org.qf</groupId>
<artifactId>M_SSS_War</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<description>这是整合的Spring和SpringMVC和Sprng Data</description>
<dependencies>
<!-- jsp页面支持JSTL标签库 -->
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.36</version>
</dependency>
</dependencies>
</project>
接下来开始代码的编写:
3、domain层
@Entity
@Table(name="tb_student")
@NamedQuery(name="Student.querys",query="select s from Student s")
public class Student {
//@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")//日期格式化
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(length=50)
private String name;
@Column(length=2)
private String sex;
//@Basic
//@Transient只是属性不是字段
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
4、dao层
Spring Data JPA最大的改变就是dao层,只需定义接口即可,记住要继承指定的接口
public interface StudentDao extends JpaRepository<Student, Serializable>{
Student findById(int id);
Student findByIdAndName(int id,String name);
}
5、service层
public interface StudentService {
boolean save(Student stu);
List<Student> queryAll();
Student querySingle(int id);
}
@Service
public class StudentServiceImple implements StudentService{
@Autowired
private StudentDao dao;
@Override
public boolean save(Student stu) {
// TODO Auto-generated method stub
System.out.println("---->"+dao.getClass().getName());
//有主键就修改,没有主键就新增
//System.out.println(1/0);
return dao.save(stu)!=null?true:false;
}
@Override
public List<Student> queryAll() {
// TODO Auto-generated method stub
//System.out.println("数量:"+dao.count());
return dao.findAll();
}
@Override
public Student querySingle(int id) {
// TODO Auto-generated method stub
return dao.findById(id);
}
}
6、控制器层:
@Controller
public class StudentController {
@Autowired
private StudentService service;
@RequestMapping("/{jn}")
public String pre(@PathVariable String jn) {
return jn;
}
@RequestMapping("/save")
public void test1(Student stu) {
if (stu!=null &&stu.getName()!=null &&stu.getName().length()>0 ) {
stu.setId(2);
System.out.println("控制器:新增:" + service.save(stu));
}
}
@RequestMapping("/queryall")
public void test2(Model m) {
System.out.println("控制器:查询全部");
if (!m.containsAttribute("list")) {
m.addAttribute("list", service.queryAll());
}
}
@RequestMapping("/querysingle")
public String test3(int id, Model m) {
System.out.println("控制器:查询单个");
List<Student> list=new ArrayList<>();
list.add(service.querySingle(id));
m.addAttribute("list", list);
return "queryall";
}
}
7、页面,都是jsp页面
新增数据页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>新增学生</title>
</head>
<body>
<form action="save">
姓名:<input name="name"/><br/>
性别:<input name="sex"/><br/>
年龄:<input name="age"/><br/>
<input type="submit" value="新增学生"/><br/>
</form>
<a href="queryall">查询所有学生</a>
</body>
</html>
查询数据页面:
<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>所有学生</title>
</head>
<body>
<a href="queryall">刷新数据</a>
<a href="save">添加学生</a>
<table width="70%" align="center" border="1">
<c:forEach items="${list }" var="s">
<tr>
<td>${s.id }</td>
<td>${s.name }</td>
<td>${s.sex }</td>
<td>${s.age }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
8、数据库连接信息的配置文件persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<!--持久模块名称 -->
<persistence-unit name="dbconfig" transaction-type="RESOURCE_LOCAL">
<!--标记持久层的具体实现 -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!--数据库连接属性信息 -->
<properties>
<!--配置数据库驱动 -->
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<!--配置数据库url -->
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/sss_sys?characterEncoding=UTF-8" />
<!--配置数据库用户名 -->
<property name="hibernate.connection.username" value="lx" />
<!--配置数据库密码 -->
<property name="hibernate.connection.password" value="lx" />
<!--配置Hibernate方言 -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect" />
<!--设置外连接抓取树的最大深度 -->
<property name="hibernate.max_fetch_depth" value="10" />
<!--自动输出schema创建DDL语句 -->
<property name="hibernate.hbm2ddl.auto" value="create" />
<!-- 显示SQL -->
<property name="hibernate.show_sql" value="true" />
<!--格式化SQL语句 -->
<property name="hibernate.format_sql" value="true" />
<property name="javax.persistence.validation.mode" value="none"/>
</properties>
</persistence-unit>
</persistence>
9、Spring的配置文件applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<!-- 开启IOC注解扫描 -->
<context:component-scan base-package="cn.code404" >
<!--必须排除掉控制器 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--跟之前的sessionFactory,JPA操作数据库 -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!--持久模块名称 -->
<property name="persistenceUnitName" value="dbconfig"></property>
<!--数据库连接信息的配置文件 -->
<property name="persistenceXmlLocation" value="classpath:persistence.xml"></property>
<!--jpa适配器 -->
<property name="jpaVendorAdapter">
<!--基于hibernate的 -->
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
</bean>
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<!--事物添加的机制 -->
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- 启用 annotation事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置Spring Data JPA扫描目录 -->
<!-- 自动扫描并注入Spring Data JPA -->
<jpa:repositories base-package="cn.code404" transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory" />
</beans>
10、SpringMVC的配置文件springMVC.xml
<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描控制器所在的包 -->
<context:component-scan base-package="org.qf.web.controller" />
<mvc:annotation-driven>
<!--注册转换器 -->
<mvc:message-converters register-defaults="true">
<!-- @ResponseBody乱码问题,将StringHttpMessageConverter的默认编码设为UTF-8 -->
<beans:bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<beans:constructor-arg value="UTF-8" />
</beans:bean>
<!-- 配置Fastjson支持 -->
<beans:bean
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!--设置编码格式 -->
<beans:property name="charset" value="UTF-8" />
<!--支持的类型 -->
<beans:property name="supportedMediaTypes">
<beans:list>
<beans:value>application/json</beans:value>
<beans:value>text/html;charset=UTF-8</beans:value>
</beans:list>
</beans:property>
<!--写出规则 -->
<beans:property name="features">
<beans:list>
<beans:value>WriteMapNullValue</beans:value>
<beans:value>QuoteFieldNames</beans:value>
<beans:value>WriteDateUseDateFormat</beans:value>
<beans:value>WriteEnumUsingToString</beans:value>
</beans:list>
</beans:property>
</beans:bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--放行静态资源 -->
<mvc:default-servlet-handler />
<!--视图解析器,可以设置页面的前缀和后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
11、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_2_5.xsd" version="2.5">
<display-name>M_SSS_War</display-name>
<!--Spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--SpringMVC -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
ok,发布到Tomcat即可进行操作
Spring+SpringMVC+Spring Data JPA完美整合的更多相关文章
- SSM(Spring+SpringMVC+Mybatis)框架环境搭建(整合步骤)(一)
1. 前言 最近在写毕设过程中,重新梳理了一遍SSM框架,特此记录一下. 附上源码:https://gitee.com/niceyoo/jeenotes-ssm 2. 概述 在写代码之前我们先了解一下 ...
- spring(一)--spring/springmvc/spring+hibernate(mybatis)配置文件
这篇文章用来总结一下spring,springmvc,spring+mybatis,spring+hibernate的配置文件 1.web.xml 要使用spring,必须在web.xml中定义分发器 ...
- javaweb各种框架组合案例(四):maven+spring+springMVC+spring data jpa(hibernate)【失败案例】
一.失败案例 1. 控制台报错信息 严重: Exception sending context initialized event to listener instance of class org. ...
- spring + springMVC + spring Data + jpa + maven 项目框架搭建
首先看一下项目结构: 所用到的jar(pom.xml): <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:x ...
- Spring+SpringMVC+Mybatis+Maven+CXF+WebService整合之服务端
WebService服务端项目结构: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="h ...
- SSM(spring,springMVC,Mybatis)框架的整合
这几天想做一个小项目,所以搭建了一个SSM框架. 1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Joh ...
- (4)Maven快速入门_4在Spring+SpringMVC+MyBatis+Oracle+Maven框架整合运行在Tomcat8中
利用Maven 创建Spring+SpringMVC+MyBatis+Oracle 项目 分了三个项目 Dao (jar) Service (jar) Controller (web) ...
- 搭建Spring + SpringMVC + Mybatis框架之三(整合Spring、Mybatis和Spring MVC)
整合Spring和SpringMVC 之前已经整合了spring和mybatis,现在在此基础上整合SSM. 项目目录: 思路:SpringMVC的配置文件独立,然后在web.xml中配置整合. (1 ...
- spring ,springmvc,mybatis 最基本的整合,没有多余的jar包和依赖 2018.9.29日
最基本的ssm框架整合 本案例采用2018商业版intellij idea 编辑器 maven项目管理工具 tomcat8.5 接着上一篇使用springmvc最基本配置开始 https: ...
随机推荐
- Go语言IDE远程连接Linux服务器
我因为在自己的云服务器上面进行Go语言开发,IDE必不可少,为了减少对于服务器的压力决定使用golang远程连接进行开发: 首先准备goland https://www.jetbrains.com/g ...
- 如何让自己的Dev C++用上C++11标准
首先确保Dev C++版本是最新的5.11版 其实用C++11标准的语法去运行还是会出现结果的,最多warning一下 但完美主义者是不允许这样的 我们可以点击菜单栏的“工具”->“编译选项”进 ...
- 1.2 管理 NetBackup 许可证
关于管理 NetBackup 许可证 NetBackup许可证密钥是在安装软件时添加的.对于需要单独购买的选件,可以稍 后在"许可证密钥"对话框中添加许可证. 注意:在进行任何许可 ...
- Linux——Pxe+Nfs+Kickstart自动部署安装Centos7.4
PXE简介 PXE,全名Pre-boot Execution Environment,预启动执行环境:通过网络接口启动计算机,不依赖本地存储设备(如硬盘)或本地已安装的操作系统:由Intel和Syst ...
- Educational Codeforces Round 68 E. Count The Rectangles
Educational Codeforces Round 68 E. Count The Rectangles 传送门 题意: 给出不超过\(n,n\leq 5000\)条直线,问共形成多少个矩形. ...
- vue router 中,children 中 path 为空字符串的路由,是默认打开的路由(包括在 el-tabs 中嵌套路由的情况)
详见该页面的最后一个代码块:https://router.vuejs.org/zh/guide/essentials/nested-routes.html#%E5%B5%8C%E5%A5%97%E8% ...
- datagrid 溢出文本显示省略号 转载
http://www.jeasyuicn.com/?sort=3 .datagrid-cell, .datagrid-cell-group, .datagrid-header-rownumber, . ...
- BJOI2018 day2
双人猜数游戏 Alice 和 Bob 是一对非常聪明的人,他们可以算出各种各样游戏的最优策略.现在有个综艺节目<最强大佬>请他们来玩一个游戏.主持人写了三个正整数 \(s\) .\(m\) ...
- 推荐系统(recommender systems):预测电影评分--问题描述
推荐系统很重要的原因:1>它是机器学习的一个重要应用2>对于机器学习来说,特征是非常重要的,对于一些问题,存在一些算法能自动帮我选择一些优良的features,推荐系统就可以帮助我们做这样 ...
- tasklist /m
\>tasklist /m explorer*映像名称 PID 模块 = ...