springboot整合spring-data-jpa,mybatis,redis,junit

Posted 苏格拉的底

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot整合spring-data-jpa,mybatis,redis,junit相关的知识,希望对你有一定的参考价值。

新建springboot项目

(也可以新建maven项目,再导入springboot的jar包,生成springboot)https://start.spring.io/ 在线快速生成springboot工程
先上目录结构
在这里插入图片描述

整合spring-data-jpa

  • pom.xml文件添加的依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <!--            <version>1.4.4.RELEASE</version>-->
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--            <version>5.1.26</version>-->
            <!--            <scope>runtime</scope>-->
        </dependency>
  • 实体类user
  • package com.springboot.entity;
import javax.persistence.*;
import java.io.Serializable;

/**
 * 用户实体类
 */
@Entity
@Table(name="sys_user")
public class User implements Serializable {

    @Id
    @Column(name = "id")//这个是JPA注解配置
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username")//这个得跟数据库表字段一样 win下mysql不区分大小写,linux下区分  mybatis的得跟数据库字段一样
    private String username;

    @Column(name = "email")
    private String email;

    @Column(name = "password")
    private String password;

    @Column(name = "phonenum")
    private String phonenum;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPhonenum() {
        return phonenum;
    }

    public void setPhonenum(String phonenum) {
        this.phonenum = phonenum;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\\'' +
                ", email='" + email + '\\'' +
                ", password='" + password + '\\'' +
                ", phonenum='" + phonenum + '\\'' +
                '}';
    }
}
  • IUserDao
package com.springboot.dao;

import com.springboot.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 *用户持久层接口
 */
@Repository("userDao")//没写daoimpl持久层写这个
public interface IUserDao extends JpaRepository<User, Long> {//JpaRepository<User, Long>操作哪个实体类 主键   写这个底下的方法不用写

    /**
     * 查询所有用户
     */
//    List<User> findAll();
//    因为继承了extends JpaRepository 所以方法不用写
}
  • IUserService
package com.springboot.service;

import com.springboot.entity.User;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户业务层接口
 */
@Service
public interface IUserService {

    /**
     * 查询所有用户
     * @return
     */
    List<User> findAllUser();



}

  • IUserviceImpl
package com.springboot.service.impl;

import com.springboot.dao.IUserDao;
import com.springboot.dao.IUserMapper;
import com.springboot.entity.User;
import com.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户业务层实现类
 */
@Service("userService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao userDao;//spring data jpa的实现
    private IUserMapper userMapper;

    @Override
    public List<User> findAllUser() {
        return userDao.findAll();
    }

}

  • UserController
package com.springboot.controller;

import com.springboot.entity.User;
import com.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用户的控制器
 */
//@EnableAutoConfiguration
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    jpa
    @RequestMapping("/findAll")
    public List<User> findAllUser(){
        List<User> users = userService.findAllUser();

        return users;
    }





}

  • user.html
  • 在resources文件夹下新建static文件夹,只能叫这个名字。
    在这里插入图片描述
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <title>人员信息</title>
    <link rel="stylesheet" type="text/css" href="ui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="ui/themes/icon.css">
    <script type="text/javascript" src="ui/themes/jquery.min.js"></script>
    <script type="text/javascript" src="ui/themes/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="ui/locale/easyui-lang-zh_CN.js"></script>
</head>
<body>



<table id="grid" title="人员信息表" style="width:700px;height:250px"
       toolbar="#toolbar" idField="id"
       rownumbers="true" fitColumns="true" singleSelect="true">
</table>
</body>
<script type="text/javascript">
    $(function (){
        $('#grid').datagrid({
            url: 'user/findAll/',//UserController的User RequestMapping("/findAll")
            columns: [[
                {field: 'id', title: '编号', width: 60},
                {field: 'username', title: 'username', width: 60},
                {field: 'email', title: 'email', width: 60},
                {field: 'password', title: 'password', width: 60},
                {field: 'phonenum', title: 'phonenum', width: 60},
            ]]
        });
    })
</script>
</html>

ui用的easyui,方便数据传输。

  • application.properties
#springboot核心配置文件

#DB Configuration
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://47.100.248.249:3306/zxDB
spring.datasource.username=zou_web
spring.datasource.password=zou_123456


#SPRING DATA JPA Configuration
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
  • 然后运行springboot主application

在这里插入图片描述

页面地址》》http://localhost:8080/user/findAll http://localhost:8080/user.html

整合mybatis

pom.xml文件先加入依赖

<!--        整合mybatis-->
                <dependency>
                    <groupId>org.mybatis.spring.boot</groupId>
                    <artifactId>mybatis-spring-boot-starter</artifactId>
                    <version>1.3.2</version>
                </dependency>
  • 实体类同上整合jpa的user,但是字段得跟数据库字段一样,这是mybatis的区别

  • 在这里插入图片描述

  • dao接口使用Mapper》》IUserMapper

package com.springboot.dao;

import com.springboot.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 使用mybatis实现对数据库的操作接口
 */

@Mapper//要求mybatis版本3.3》=
public interface IUserMapper {

    @Select("select * from sys_user where username like '%${value}%'")
    public List<User> findUserByName(String username);

}
  • IUserService方法
List<User> findAllUser(String username);
  • UserviceImpl
//    mybatis
    @Override
    public List<User> findAllUser(String username) {
        return userMapper.findUserByName(username);
    }
  • UserController
//    mybatis
    @RequestMapping("/findAll/{username}")
    public List<User> findAllUser(@PathVariable("username") String username){
        List<User> users = userService.findAllUser(username);
        //http://localhost:8080/user/findAll/1
        return users;
    }
  • user.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <title>人员信息</title>
    <link rel="stylesheet" type="text/css" href="ui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="ui/themes/icon.css">
    <script type="text/javascript" src="ui/themes/jquery.min.js"></script>
    <script type="text/javascript" src="ui/themes/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="ui/locale/easyui-lang-zh_CN.js"></script>
</head>
<body>



<table id="grid" title="人员信息表" style="width:700px;height:250px"
       toolbar="#toolbar" idField="id"
       rownumbers="true" fitColumns="true" singleSelect="true">
</table>
</body>
<script type="text/javascript">
    $(function (){
        $('#grid').datagrid({
            url: 'user/findAll/1',//mybatis 根据方法条件查询 UserController的User RequestMapping("/findAll")
            columns: [[
                {field: 'id', title: '编号', width: 60},
                {field: 'username', title: 'username', width: 60},
                {field: 'email', title: 'email', width: 60},
                {field: 'password', title: 'password', width: 60},
                {field: 'phonenum', title: 'phonenum', width: 60},
            ]]
        });
    })
</script>
</html>

整合Redis

  • 需要win下安装redis 再运行redis(redis-server.exe运行) Redis Desktop
    Manager软件管理redis
  • pom.xml先加入依赖
<!--        整合redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.3.8.RELEASE</version>
        </dependency>
  • User 实体类同上没有改变
  • IUserMapper
//    redis
    @Select("select * from sys_user")
    List<User> findAll();
  • IUserService
/**
     * redis使用
     * 查询所有
     * @return
     */
    List<User> findAll();
  • UserServiceImpl
//    redis
    @Override
    @Cacheable(value = "findAllCache",key = "'user.findAll'")//表示当前方法使用缓存,并存入redis数据库中
//    @Cacheable(value = "findAllCache",Key="'djkjkdk'")//表示当前方法使用缓存,并存入redis数据库中
//                value属性:表示存入redis数据库的key
//    key属性 用于指定方法返回值的key,该属性是spring用的,不屑也有默认值
    public List<User> findAll() {
        System.out.println("执行去数据库查询");
        return userMapper.findAll();
    }
  • UserController
//    redis
    @RequestMapping("/findAll")
    public List<User> findAll(){
        List<User> users = userService.findAll();
        return users;
    }
  • user.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <title>人员信息</title>
    <link rel="stylesheet" type="text/css" href="ui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="ui/themes/icon.css">
    <script type="text/javascript" src="ui/themes/jquery.min.js"></script>
    <script type="text/javascript" src="ui/themes/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="ui/locale/easyui-lang-zh_CN.js"></script>
</head>
<body>



<table id="grid" title="人员信息表" style="width:700px;height:250px"
       toolbar="#toolbar" idField="id"
       rownumbers="true" fitColumns="true" singleSelect="true">
</table>
</body>
<script type="text/javascript">
    $(function (){
        $('#grid').datagrid({
            // url: 'user/findAll/',//UserController的User RequestMapping("/findAll")
            // url: 'user/findAll/1',//mybatis 根据方法条件查询 UserController的User RequestMapping("/findAll")
            url: 'user/findAll',//redis UserController的User RequestMapping("/findAll")
            columns: [[
                {field: 'id', title: '编号', width: 60},
                {field: 'username', title: 'username', width: 60},
                {field: 'email', title: 'email', width: 60},
                {field: 'password', title: 'password', width: 60},
                {field: 'phonenum', title: 'phonenum', width: 60},
            ]]
        });
    })
</script>
</html>

整合JUnit

  • pom.xml先添加依赖
<!--整合Junit-->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  • 新建一个test包
创建SpringBootJunitTest.java
package com.springboot.test;

import com.springboot.service.IUserService;
import javafx.application.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.omg.CORBA.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.List;

/**
 * springboot整合Junit
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)//属性用于指定引导类
public class SpringBootJunitTest {

    @Autowired
    private IUserService userService;

    @Test
    public void testFindAll(){
        List list = userService.findAll();
        System.out.println(list);
    }

//    https://www.cnblogs.com/muliu/p/8252971.html
//    读取springboot核心配置文件的方式
//    @Resource
//    private Environment env;
//
//    @Test
//    public void testReadSpringBootConfig(){
//        System.out.println(env.getProperty("spring.datasource.url"));
//    }



}

以上是关于springboot整合spring-data-jpa,mybatis,redis,junit的主要内容,如果未能解决你的问题,请参考以下文章

[SpringBoot系列]SpringBoot如何整合SSMP

springboot怎么整合activiti

SpringBoot完成SSM整合之SpringBoot整合junit

springboot整合jedis

SpringBoot 整合其他框架 -- SpringBoot整合Mybatis

SpringBoot 整合其他框架 -- SpringBoot整合Junit