SpringBoot JPA

一、创建步骤在这里插入图片描述在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

二、目录结构

在这里插入图片描述

三、application.properties配置datasource

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost/springboot?userUnicode=true@characterEncoding=UTF8&serverTimezone=UTC

四、domain层创建实体类User

在这里插入图片描述

package com.willam.domain;

import javax.persistence.*;

/**
 * @author :lijunxuan
 * @date :Created in 2019/6/28  17:04
 * @description :
 * @version: 1.0
 */
@Table(name = "user")
@Entity
public class User {
    @Id  //ID代表是主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)  //按照主键自增
    private Integer id;
    //@Column(name="username")   //把数据库里的名字和当前名字做一个绑定关系
    private String  username;
    private String  password;
    private String  name;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", name='" + name + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

五、Controller层UserController

在这里插入图片描述

package com.willam.Controller;

import com.willam.Service.UserService;
import com.willam.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author :lijunxuan
 * @date :Created in 2019/6/28  17:02
 * @description :
 * @version: 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 查询所有用户
     * @return
     */
    @RequestMapping("/findAll")
    public List<User> findAll(){
                       return userService.findAll();
                 }

    /**
     * 通过ID查询用户
     * @param id
     * @return
     */
    @RequestMapping("/findById")
                public User findById(Integer id){
                    return userService.findById(id);
                }

    /**
     * 添加用户
     * @param user
     *
     */
    @RequestMapping("/add")
                public void add(User user){
                   userService.add(user);
                }

    /**
     * 通过用户ID删除用户
     * @param id
     *
     */
    @RequestMapping("/deleteById")
    public void deleteById(Integer id){
         userService.deleteById(id);
    }


}

六、service层

(1)UserService接口

package com.willam.Service;

import com.willam.domain.User;

import java.util.List;

public interface UserService {
    /**
     * 查询所有用户信息
     * @return
     */
    List<User> findAll();
    /**
     * 通过ID查询用户
     * @param id
     * @return
     */
    User findById(Integer id);
    /**
     * 添加用户
     * @param user
     *
     */
    void add(User user);
    /**
     * 通过用户ID删除用户
     * @param id
     *
     */
    void deleteById(Integer id);
}

(2)UserServiceImpl实现类

package com.willam.Service.impl;

import com.willam.Dao.UserDao;
import com.willam.Service.UserService;
import com.willam.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author :lijunxuan
 * @date :Created in 2019/6/28  17:27
 * @description :
 * @version: 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }
    @Override
    public User findById(Integer id) {
        Optional<User> userById = userDao.findById(id);
        return userById.get();
    }
    @Override
    public void add(User user) {
      userDao.save(user);
    }
    @Override
    public void deleteById(Integer id) {
   userDao.deleteById(id);
    }
}

七、Dao层

在这里插入图片描述

package com.willam.Dao;

import com.willam.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserDao extends JpaRepository<User,Integer> {
}

八、 集成Spring Data Redis

实现步骤:

  1. 添加Redis起步依赖
  2. 在application.properties中配置redis端口、地址
  3. 注入RedisTemplate操作Redis缓存查询所有用户数据
  4. 测试缓存

1. 添加Redis起步依赖

 <!--redis起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2. 在application.properties中配置redis端口、地址

# Redis 配置(不填也是可以的)
spring.redis.host=localhost
spring.redis.port=6379

3. 注入RedisTemplate操作Redis缓存查询所有用户数据

将Controller层的findAll方法修改一下
    @Resource
    RedisTemplate redisTemplate;
    @RequestMapping("/findAll")
    public List<User> findAll(){

        /*如果第一次查询,redis缓存没有数据,就从数据库中获取
        如果有缓存数据,那么从缓存中获取
       */
        String users = (String)redisTemplate.boundValueOps("userDao.findAll").get();
        if (users==null){
            //数据库查询
           List<User> all=userService.findAll();
           users = all.toString();
           redisTemplate.boundValueOps("userDao.findAll").set(users);  //把当前的数据缓存
        }
        return userService.findAll();
                 }

4. 测试缓存

打一个断点
在这里插入图片描述
地址栏 发送请求 http://localhost:8080/user/findAll
在这里插入图片描述
后台
在这里插入图片描述
redis中有缓存则直接走 return userService.findAll();
在这里插入图片描述
在这里插入图片描述

九、 集成定时器

(1)在SpringbootJpaApplication开启定时器

在这里插入图片描述

(2)创建Timer类

在这里插入图片描述

package com.willam.Utils;

import com.willam.Service.UserService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author :lijunxuan
 * @date :Created in 2019/6/28  19:18
 * @description :
 * @version: 1.0
 */
@Component //把当前的类加入spring容器
public class Timer {
    UserService userService;
    /**
     * 定时任务的配置
     * corn 表达式
     * fixedDelay 固定的延迟时间执行,上一个任务执行完成,多久之后下一个任务执行。
     * rateDelay 固定频率执行,每隔固定时间执行任务
     */
    @Scheduled(fixedRate = 2000)
    public void task(){
        System.out.println(new Date());
        System.out.println(LocalDateTime.now());
    }
}

(3)测试结果

每隔2秒执行一次
在这里插入图片描述

十、SpringBoot如何代码测试

(1)加入依赖

 <!--springBoot的测试依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

(2)编写测试类:

  • SpringRunner继承SpringJUnit4ClassRunner,使用哪一个Spring提供的测试引擎都可以。指定运行测试的引擎
  • @SpringBootTest的属性值指的是引导类的字节码对象
package com.willam;

import com.willam.Service.UserService;
import com.willam.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest //SpringBoot测试类
public class SpringbootJpaApplicationTests {
    @Resource
    UserService userService;

    @Test
    public void contextLoads() {
        List<User> userList = userService.findAll();
        System.out.println(userList);
    }

}

(3)测试结果

在这里插入图片描述

十一、Spring Boot 如何打包部署

(1)打成Jar包部署

在cmd切换到项目的路径
如:H:\workspace\IdeaProject\SpringBoot\day01\day01_springboot_jpa
在这里插入图片描述
在这里插入图片描述
启动命令:

java -jar target/day01_springboot_jpa-0.0.1-SNAPSHOT.jar

在这里插入图片描述
启动命令的时候配置jvm参数也是可以的。然后查看一下Java的参数配置结果

java -Xmx80m -Xms20m  -jar target/day01_springboot_demo01-1.0-SNAPSHOT.jar

小技巧

在这里插入图片描述

(2)打成War包部署

1.执行maven打包命令或者使用IDEA的Maven工具打包,需要修改pom.xml文件中的打包类型。
<packaging>war</packaging>
2. 注册启动类
  • 创建 ServletInitializer.java,继承 SpringBootServletInitializer ,覆盖 configure(),把启动类 Application 注册进去。外部 Web 应用服务器构建 Web Application Context 的时候,会把启动类添加进去

在这里插入图片描述

//web.xml
public class ServletInitializer extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(DemoApplication.class);
    }
}
3.然后执行打包操作

在这里插入图片描述

启动

在这里插入图片描述

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值