文章内容输出来源:拉勾教育Java高薪训练营
Spring + SpringMvc + Spring Data Jpa框架整合
本篇博客,我们来说下spring 整合 spring mvc 和 spring data jpa的整个过程 先来看下项目结构 我把配置文件拆分为spring-mvc.xml 和spring-jpa.xml两个文件,使用 jdbc.properties来配置数据源
准备
数据库脚本
CREATE TABLE `tb_resume` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`phone` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_resume
-- ----------------------------
BEGIN;
INSERT INTO `tb_resume` VALUES (1, '成龙', '北京朝阳', '17611222456');
INSERT INTO `tb_resume` VALUES (2, '甄子丹', '北京海淀', '10086');
INSERT INTO `tb_resume` VALUES (3, '谢霆锋', '河南郑州', '10086');
COMMIT;
整合需要的jar
<?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>org.example</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>spring-data-jpa Maven Webapp</name>
<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>
<spring.version>5.2.8.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
<!--hibernate对jpa的实现jar-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.21.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.6.Final</version>
</dependency>
<!--hibernate相关jar包,end-->
<!--spring相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!--数据库驱动jar-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!--集成spring mvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.1</version>
</dependency>
<!--jsp-api&servlet-api-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>ssm</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<target>8</target>
<source>8</source>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
接下来我来说下如何进行集成
1. spring 集成 spring data jpa
1.1 数据源配置文件jdbc.properties
这里我们使用的数据库是MySQL
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
1.1 Jpa配置文件 spring-jpa.xml
我们先来配置一下数据源,因为我们用properties文件来进行配置的,所以我们需要引入下配置文件,然后引入数据源,这里数据源我们使用的是阿里的Druid
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
">
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
接下来配置spring 的包扫描
<context:component-scan base-package="com.lagou"/>
接下来就配置jpa的EntityManagerFactory以及jpa的事务管理器还有jpa dao层的一些细节,比如配置dao层所在的包,指定EntityManagerFactory以及事务管理器
<!--配置EntityManagerFactory-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!--数据源-->
<property name="dataSource" ref="dataSource"/>
<!--配置包扫描(实体所在包)-->
<property name="packagesToScan" value="com.lagou.pojo"/>
<!--指定jpa的具体实现,这里用的hibernate-->
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
<!--指定方言-->
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
<!--配置具体的provider hibernate框架执行细节-->
<property name="jpaVendorAdapter" >
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--指定数据库类型-->
<property name="database" value="MYSQL"/>
<!--程序启动之后是否需要给数据库创建映射表-->
<property name="generateDdl" value="false"/>
<!--是否打印sql-->
<property name="showSql" value="true"/>
<!--配置数据库方言,根据不同数据库执行各自的语法-->
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
</bean>
</property>
</bean>
<!--配置jpa事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--配置jpa dao层细节-->
<jpa:repositories base-package="com.lagou.dao" entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager"/>
到这里,我们关于jpa的配置以及完全结束。
1.3 Jpa 实体对象配置Resume.java
配置一个Jpa对象需要使用到一下注解
@Entity 告诉Jpa,这是我们配置的一个实体类
@Table 指定类和数据库表映射关系
@Id 标记主键ID
@GeneratedValue 主键生成策略,根据不同的数据库可以配置不同的策略
@Column 指定实体属性和数据库表中属性的对应关系
@Entity @Table(name = "tb_resume") @Data @ToString public class Resume { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "name") private String name; @Column(name = "address") private String address; @Column(name = "phone") private String phone; }
1.4 配置Jpa dao层接口ResumeDao.java
想要使用jpa提供的数据库操作方法,我们需要继承JpaRepository
和JpaSpecificationExecutor
两个接口,这里可能有同学会问了,java不是单继承吗? 注意,这里的ResumeDao
是接口,接口是可以多继承的。 JpaRepository
和JpaSpecificationExecutor
这两个接口提供了我们常用的一些增删改查操作,继承之后就不需要我们自己写这些SQL操作了。
public interface ResumeDao extends JpaRepository<Resume, Integer>, JpaSpecificationExecutor<Resume> {
}
1.5 整合测试
以上我们所有jpa相关的配置都以及完成了,接下来我们来测试下,我们的配置有没有问题 测试类ResumeDaoTest.java
这里我们使用junit4来进行测试,里面有两个测试用例,查询所有和添加,我们分别来测试下
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:spring-*.xml"})
public class ResumeDaoTest {
@Autowired
private ResumeDao resumeDao;
@Test
public void findAll() {
List<Resume> all = resumeDao.findAll();
System.out.println(all);
}
@Test
public void add() {
Resume resume = new Resume();
resume.setName("王五");
resume.setAddress("Henan");
resume.setPhone("17611222722");
System.out.println(resumeDao.save(resume));
}
}
findAll()
add() 可以看到,查询和添加都正常,接下来我们看下和springmvc的集成
2. spring 集成springMvc
2.1 配置文件spring-mvc.xml
相较于jpa的整合,spring mvc的整合就简单了一点,都比较简单,我们就不解释了
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
<context:component-scan base-package="com.lagou.controller"/>
<mvc:annotation-driven/>
<!--配置spring mvc的视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
<mvc:resources location="/layer/" mapping="/layer/**"/>
</beans>
2.2 Servlet配置文件web.xml
主要是配置spring mvc的监听类DispatcherServlet
,配置一下拦截路径,这里我们直接拦截出了jsp之外的所有文件。另外为了防止字符乱码,这里我们配置了字符过滤器
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<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"
id="WebApp_ID" version="2.5">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>/jsp/login.jsp</welcome-file>
</welcome-file-list>
<!--配置编码过滤器-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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-*.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2.3 配置controller ResumeController.java
这里我们配置了针对resume的基本增删改查操作,以及一些跳转操作
@Controller
@RequestMapping("/resume")
public class ResumeController {
@Resource
private ResumeService resumeService;
@RequestMapping(value = "/getAll", method = RequestMethod.GET)
@ResponseBody
public Result getAll() {
return resumeService.getResumeList();
}
@RequestMapping(value = "/toAdd")
public String addResume() {
return "addResume";
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public Result addResume(@RequestBody Resume resume) {
return resumeService.addResume(resume);
}
@RequestMapping("/update")
@ResponseBody
public Result toUpdate(@RequestBody Resume resume) {
return resumeService.updateResume(resume);
}
@RequestMapping("/toUpdate/{id}")
public String toUpdateResume(@PathVariable("id") Integer id, ModelMap modelMap) {
Result resume = resumeService.getResumeById(id);
modelMap.addAttribute("resume", resume.getResult());
return "editResume";
}
@RequestMapping("/delete/{id}")
@ResponseBody
public Result deleteResume(@PathVariable("id") Integer id) {
return resumeService.deleteResume(id);
}
}
2.4 配置service接口ResumeService
public interface ResumeService {
Result getResumeList();
Result getResumeById(Integer id);
Result addResume(Resume resume);
Result updateResume(Resume resume);
Result deleteResume(Integer id);
}
2.5 配置service实现类ResumeServiceImpl.java
@Service
public class ResumeServiceImpl implements ResumeService {
@Resource
private ResumeDao resumeDao;
@Override
public Result getResumeList() {
return ResultUtils.success(resumeDao.findAll());
}
@Override
public Result getResumeById(Integer id) {
Optional<Resume> resume = resumeDao.findById(id);
return ResultUtils.success(resume.orElse(null));
}
@Override
public Result addResume(Resume resume) {
return ResultUtils.success(resumeDao.save(resume));
}
@Override
public Result updateResume(Resume resume) {
return ResultUtils.success(resumeDao.save(resume));
}
@Override
public Result deleteResume(Integer id) {
Optional<Resume> resume = resumeDao.findById(id);
if (!resume.isPresent()) {
return ResultUtils.error(500, "请求删除对象未找到");
}
resumeDao.delete(resume.get());
return ResultUtils.success();
}
}
2.6 测试
其实项目中我们实现了一个简单的登录,以及针对resume的增删改查操作,因为这不是我们关注的重点,所以我就不贴代码了,想要完整项目的可以去我的码云上面下载完整代码 我们直接看测试情况
总结
以上就是我们整合的全部过程,希望对初学者有点帮助,想要完整代码的可以点下面链接获取完整代码 https://gitee.com/tengfei-wang/spring-data-jpa