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即可进行操作