Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to integrate Spring+SpringMvc+Spring Data Jpa Framework

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to integrate the Spring+SpringMvc+Spring Data Jpa framework, the article is very detailed, has a certain reference value, interested friends must read it!

Spring + SpringMvc + Spring Data Jpa framework integration

Let's talk about the whole process of spring integrating spring mvc and spring data jpa. Let's first take a look at the project structure. I split the configuration file into two files, spring-mvc.xml and spring-jpa.xml, and use jdbc.properties to configure the data source.

Prepare database scripts 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, 'Jackie Chan', 'Beijing Chaoyang', '17611222456'); INSERT INTO `tb_ resume`VALUES (2, 'Donnie yen', 'Beijing Haidian', '10086') INSERT INTO `tb_ resume` VALUES (3, 'Nicholas Tse', 'Zhengzhou, Henan', '10086'); COMMIT Jar 4.0.0 org.example spring-data-jpa 1.0-SNAPSHOT war spring-data-jpa Maven Webapp UTF-8 1.8 1.8 5.2.8.RELEASE junit junit 4.12 org.springframework.data spring required for integration -data-jpa 2.3.4.RELEASE org.hibernate hibernate-entitymanager 5.4.21.Final org.hibernate hibernate-validator 5.3.6.Final org.springframework Spring-core ${spring.version} org.springframework spring-orm ${spring.version} org.springframework spring-context ${spring.version} org.springframework spring-context-support $ {spring.version} org.springframework spring-tx ${spring.version} org.springframework spring-jdbc ${spring.version} org.springframework spring-test ${spring.version} Org.aspectj aspectjweaver 1.9.4 mysql mysql-connector-java 5.1.46 com.alibaba druid 1.1.21 org.projectlombok Lombok 1.18.12 org.springframework spring-webmvc ${spring.version} com.fasterxml.jackson.core jackson-databind 2.11.1 javax.servlet javax.servlet-api 3.1.0 provided ssm org.apache.maven.plugins maven-compiler-plugin 3.8.1 8 8 UTF-8

Next, I'm going to talk about how to integrate.

1. Spring Integration spring data jpa1.1 data Source configuration File jdbc.properties

The database we use here is MySQL.

Jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8jdbc.username=rootjdbc.password=root1.1 Jpa profile spring-jpa.xml

Let's first configure the data source, because we use the properties file to configure, so we need to introduce the next configuration file, and then introduce the data source, where we use Ali's Druid

Next, configure spring's packet scan.

Next, configure the EntityManagerFactory of jpa and the transaction manager of jpa as well as some details of the jpa dao layer, such as configuring the package where the dao layer is located, specifying EntityManagerFactory and the transaction manager.

At this point, we have a complete end to the configuration of jpa.

1.3 Jpa entity object configuration Resume.java

You need to use the following annotations to configure a Jpa object

@ Entity tells Jpa that this is an entity class that we configured

@ Table specifies the mapping relationship between classes and database tables

@ Id tag primary key ID

@ GeneratedValue primary key generation policy, which can be configured according to different databases

@ Column specifies the correspondence between the entity attributes and the attributes in the database table

@ Entity@Table (name = "tb_resume") @ Data@ToStringpublic 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 configure Jpa dao layer interface ResumeDao.java

In order to use the database operation method provided by jpa, we need to inherit JpaRepository and JpaSpecificationExecutor interfaces. Some students here may ask, isn't java a single inheritance? Note that the ResumeDao here is the interface, and the interface can be inherited more than once. JpaRepository and JpaSpecificationExecutor provide some common add, delete, modify and search operations. After inheritance, there is no need for us to write these SQL operations.

Public interface ResumeDao extends JpaRepository, JpaSpecificationExecutor {} 1.5 integration test

All of the above jpa-related configurations have been completed. Next, let's test whether there are any problems with our configuration. Here we use junit4 to test the class ResumeDaoTest.java. There are two test cases, query all and add them. Let's test them respectively.

@ RunWith (SpringJUnit4ClassRunner.class) @ ContextConfiguration (locations = {"classpath*:spring-*.xml"}) public class ResumeDaoTest {@ Autowired private ResumeDao resumeDao; @ Test public void findAll () {List all = resumeDao.findAll (); System.out.println (all);} @ Test public void add () {Resume resume = new Resume (); resume.setName (Wang Wu); resume.setAddress ("Henan") Resume.setPhone ("17611222722"); System.out.println (resumeDao.save (resume));}}

FindAll ()

Add ()

As you can see, both queries and additions are normal, so let's take a look at the integration with springmvc

2. Spring integrated springMvc2.1 configuration file spring-mvc.xml

Compared with the integration of jpa, the integration of spring mvc is a little simpler, which is relatively simple, so we won't explain it.

2.2 Servlet profile web.xml

The main task is to configure spring mvc's listener class DispatcherServlet and intercept path. Here we directly intercept all files except jsp. In addition, in order to prevent character garbled, we have configured a character filter here.

Archetype Created Web Application / jsp/login.jsp characterEncodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 forceEncoding true characterEncodingFilter / * dispatcherServlet org.springframework.web.servlet.DispatcherServlet ContextConfigLocation classpath*:spring-*.xml dispatcherServlet / 2.3Config controller ResumeController.java

Here we configure the basic add, delete, modify and search operations for resume, as well as some jump operations.

@ 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) Configure service interface ResumeServicepublic interface ResumeService {Result getResumeList (); Result getResumeById (Integer id); Result addResume (Resume resume); Result updateResume (Resume resume); Result deleteResume (Integer id);} 2.5.Configuring service implementation class ResumeServiceImpl.java@Servicepublic 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 = 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 = resumeDao.findById (id); if (! resume.isPresent ()) {return ResultUtils.error (500, "request for deletion object not found");} resumeDao.delete (resume.get ()); return ResultUtils.success ();}} 2.6Test

In fact, we have implemented a simple login in the project, as well as the addition, deletion, modification and search operation for resume, because this is not the focus of our attention, so I will not post the code. If you want a complete project, you can go to my code cloud to download the complete code. We will directly look at the test situation.

The above is all the contents of the article "how to integrate the Spring+SpringMvc+Spring Data Jpa Framework". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report