zoukankan      html  css  js  c++  java
  • Spring Boot Sample 018之spring-boot-data-jparepository

    一、环境

    • Idea 2020.1
    • JDK 1.8
    • maven

    二、目的

    spring boot整合jparepository。

    三、步骤

    3.1、点击File -> New Project -> Spring Initializer,点击next

    3.2、在对应地方修改自己的项目信息

    3.3、选择Web依赖,选中Spring Web、Spring Data JPA、MySQL Driver。可以选择Spring Boot版本,本次默认为2.2.6,点击Next

    3.4、项目结构

    四、添加文件

    pom.xml文件

    <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.7.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>org.ouyushan</groupId>
        <artifactId>spring-boot-data-jparepository</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>spring-boot-data-jparepository</name>
        <description>JPA project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
    
            <!-- 解决json与hibernate懒加载引起的问题 -->
            <dependency>
                <groupId>com.fasterxml.jackson.datatype</groupId>
                <artifactId>jackson-datatype-hibernate5</artifactId>
                <version>2.11.0</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>

    application.properties文件

    ######   mysql     #######
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    spring.datasource.username=root
    spring.datasource.password=root
    
    ######   JPA     #######
    spring.jpa.database=MYSQL
    spring.jpa.show-sql=true
    spring.jpa.generate-ddl=true
    spring.jpa.properties.hibernate.format-sql=true
    spring.jpa.hibernate.ddl-auto=update
    
    #spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
    spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
    spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    
    ######   log     #######
    logging.level.org.ouyushan.springboot.data.jparepository=debug
    JpaConfig.java
    package org.ouyushan.springboot.data.jparepository.config;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
    import org.springframework.boot.autoconfigure.domain.EntityScan;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
    import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
    
    /**
     * @Description: 需指定扫描japRepositories路径和entiry路径
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/5/8 10:00
     */
    
    @Configuration
    @EnableJpaRepositories("org.ouyushan.springboot.data.jparepository")
    @EntityScan("org.ouyushan.springboot.data.jparepository.entity")
    public class JPAConfig {
    
        /* <!-- 解决json与hibernate懒加载引起的问题 --> */
        @Bean
        public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    
            Hibernate5Module hibernate5Module = new Hibernate5Module();
            hibernate5Module.configure(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION, false);
    
            MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
            ObjectMapper objectMapper = jsonConverter.getObjectMapper();
            objectMapper.registerModule(new Hibernate5Module());
    
            return jsonConverter;
        }
    }
    UserInfoRepository.java
    package org.ouyushan.springboot.data.jparepository.repository;
    
    import org.ouyushan.springboot.data.jparepository.entity.UserInfo;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.data.jpa.repository.Modifying;
    import org.springframework.data.jpa.repository.Query;
    
    /**
     * @Description:
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/5/8 10:56
     */
    public interface UserInfoRepository extends JpaRepository<UserInfo, Long> {
    
        /* 更新 */
        @Modifying
        @Query("update UserInfo u set  u.userName = ?1, u.password = ?2, u.age = ?3  where u.id = ?4")
        int update(String userName, String password,int age,Long id);
    }
    
    
    UserInfoService.java
    package org.ouyushan.springboot.data.jparepository.service;
    
    import org.ouyushan.springboot.data.jparepository.entity.UserInfo;
    
    import java.util.List;
    
    /**
     * @Description:
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/5/8 10:58
     */
    public interface UserInfoService {
    
        UserInfo add(UserInfo userInfo);
    
        int update(UserInfo userInfo);
    
        void delete(Long id);
    
        UserInfo findUserInfo(Long id);
    
        List<UserInfo> findUserInfoList();
    }
    UserInfoServiceImpl.java
    package org.ouyushan.springboot.data.jparepository.service;
    
    import org.ouyushan.springboot.data.jparepository.entity.UserInfo;
    import org.ouyushan.springboot.data.jparepository.repository.UserInfoRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.List;
    import java.util.Optional;
    
    /**
     * @Description:
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/5/8 10:58
     */
    @Service("userInfoService")
    @Transactional
    public class UserInfoServiceImpl implements UserInfoService {
    
    
        @Autowired
        private UserInfoRepository userInfoRepository;
    
        /* 增加 */
        @Override
        public UserInfo add(UserInfo userInfo) {
            return this.userInfoRepository.save(userInfo);
        }
    
        /* 更新 */
        @Override
        public int update(UserInfo userInfo) {
            return this.userInfoRepository.update(userInfo.getUserName(), userInfo.getPassword(), userInfo.getAge(), userInfo.getId());
        }
    
        /* 删除 */
        @Override
        public void delete(Long id) {
            this.userInfoRepository.deleteById(id);
        }
    
        /* 根据id查找 */
        @Override
        public UserInfo findUserInfo(Long id) {
            Optional<UserInfo> optional = this.userInfoRepository.findById(id);
            return optional.orElse(new UserInfo());
        }
    
        /* 获取列表 */
        @Override
        public List<UserInfo> findUserInfoList() {
            return this.userInfoRepository.findAll();
        }
    }
    UserInfoController.java
    package org.ouyushan.springboot.data.jparepository.controller;
    
    import org.ouyushan.springboot.data.jparepository.entity.UserInfo;
    import org.ouyushan.springboot.data.jparepository.service.UserInfoService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    /**
     * @Description:
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/5/8 11:03
     */
    @RestController
    @RequestMapping("/api/user")
    public class UserInfoController {
    
        @Autowired
        private UserInfoService userInfoService;
    
        /**
         * 查询个人信息
         *
         * @param id
         * @return
         */
        @GetMapping(value = "/getUser/{id}")
        public UserInfo getUserInfo(@PathVariable("id") Long id) {
            UserInfo userInfo = userInfoService.findUserInfo(id);
            if (userInfo == null) {
                throw new RuntimeException("查询为空");
            }
            return userInfo;
        }
    
        /**
         * 查询用户列表
         *
         * @return
         */
        @GetMapping(value = "/getUsers")
        public List<UserInfo> getUserInfoList() {
            List<UserInfo> userInfoList = this.userInfoService.findUserInfoList();
            if (userInfoList == null || userInfoList.size() == 0) {
                throw new RuntimeException("用户列表为空");
            }
            return userInfoList;
        }
    
        /**
         * 新增用户
         */
        @PostMapping(value = "/addUser")
        public void addUser(@RequestBody UserInfo userInfo) {
            try {
                this.userInfoService.add(userInfo);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("新增用户失败");
            }
        }
    
        /**
         * 更新用户
         *
         * @param
         */
        @PutMapping(value = "/updateUser")
        public void update(@RequestBody UserInfo userInfo) {
            try {
                this.userInfoService.update(userInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        @DeleteMapping(value = "/delete/{id}")
        public void delete(@PathVariable("id") Long id) {
            try {
                this.userInfoService.delete(id);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("删除用户:" + id + " 失败");
            }
        }
    
    }

    五、测试

    SpringBootDataJparepositoryApplicationTests.java
    package org.ouyushan.springboot.data.jparepository;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.junit.jupiter.api.Test;
    import org.ouyushan.springboot.data.jparepository.entity.UserInfo;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.http.MediaType;
    import org.springframework.test.web.servlet.MockMvc;
    import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
    import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
    
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    @SpringBootTest
    @AutoConfigureMockMvc
    class SpringBootDataJparepositoryApplicationTests {
    
        private static Logger logger = LoggerFactory.getLogger(SpringBootDataJparepositoryApplicationTests.class);
    
    
        /**
         * 根据ID查询
         */
        @Test
        public void testSelectById(@Autowired MockMvc mockMvc) throws Exception {
            mockMvc.perform(MockMvcRequestBuilders.get("/api/user/getUser/{1}", 1))
                    .andDo(MockMvcResultHandlers.print()) //方法用于 打印请求、响应及其他相关信息
                    .andExpect(status().isOk())
                    .andExpect(content().json(("{"id":1,"userName":"admin","password":"123","age":28}")));
        }
    
        /**
         * 查询用户列表
         */
        @Test
        public void testSelectAll(@Autowired MockMvc mockMvc) throws Exception {
            mockMvc.perform(MockMvcRequestBuilders.get("/api/user/getUsers"))
                    .andDo(MockMvcResultHandlers.print())
                    //.andDo(print())
                    .andExpect(status().isOk());
        }
    
    
        /**
         * 添加用户
         *
         * @throws Exception
         */
        @Test
        public void testAddUser(@Autowired MockMvc mockMvc) throws Exception {
    
            UserInfo userInfo = new UserInfo();
            userInfo.setUserName("mockMvc");
            userInfo.setPassword("mockmvc");
            userInfo.setAge(24);
    
            ObjectMapper mapper = new ObjectMapper();
            String userJson = mapper.writeValueAsString(userInfo);
    
            mockMvc.perform(MockMvcRequestBuilders.post("/api/user/addUser")
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .content(userJson))
    
                    .andDo(MockMvcResultHandlers.print())
                    // .andDo(print())
                    .andExpect(status().isOk());
        }
    
    
        /**
         * 更新用户
         *
         * @throws Exception
         */
        @Test
        public void testUpdateUser(@Autowired MockMvc mockMvc) throws Exception {
    
            UserInfo userInfo = new UserInfo();
            userInfo.setId(9L);
            userInfo.setUserName("mockMvc1");
            userInfo.setPassword("mockmvc1");
            userInfo.setAge(28);
    
            ObjectMapper mapper = new ObjectMapper();
            String userJson = mapper.writeValueAsString(userInfo);
    
            mockMvc.perform(MockMvcRequestBuilders.put("/api/user/updateUser")
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .content(userJson))
    
                    .andDo(MockMvcResultHandlers.print())
                    // .andDo(print())
                    .andExpect(status().isOk());
        }
    
        /**
         * 删除
         *
         * @throws Exception
         */
        @Test
        public void testDeleteUser(@Autowired MockMvc mockMvc) throws Exception {
            mockMvc.perform(MockMvcRequestBuilders.delete("/api/user/delete/{id}", 9))
                    .andDo(MockMvcResultHandlers.print())
                    .andExpect(status().isOk());
        }
    }
  • 相关阅读:
    jQuery 之 serialize() serializeArray()
    浅析JavaScript中Function对象(二) 之 详解call&apply
    详解JavaScript作用域及作用域链
    浅析JavaScript中Function对象(一)之 arguments对象
    浅析jQuery基本结构($实现原理)
    浅析伪数组
    jQuery版本差异简要分析
    白话解释:控制反转与依赖注入
    为什么开发移动端web不使用jQuery
    浅析meta标签用处
  • 原文地址:https://www.cnblogs.com/ouyushan/p/13031155.html
Copyright © 2011-2022 走看看