SpringBoot教程(三)集成JPA(druid)构建web服务

一、本地环境

  • 操作系统:Mac OS X 10.13.2
  • 编辑器:IntelliJ IDEA 2017
  • JDK版本:jdk 1.8
  • Maven版本:apache-maven-3.5.0
  • SpringBoot版本:SpringBoot 2.0

二、pom依赖文件

<?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>com.lonelyCountry</groupId>
	<artifactId>springboot_03_hibernate</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot_03_hibernate</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<!-- JPA驱动 -->
		<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>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!-- mysql驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!-- 注解工具类 -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- google工具类 -->
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>23.5-jre</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
			    <groupId>org.springframework.boot</groupId>
			    <artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
复制代码

三、配置文件以及工程结构

1、配置文件

application.yml

server:
  port: 8080
spring:
  datasource:
    driverclassname: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot-jpa?characterEncoding=UTF-8&useSSL=false
    username: root
    password: 
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  jackson:
    serialization:
      indent-output: true
复制代码

2、目录结构

四、编写代码

1、构建Po层以及数据库表

(1)、User类
package com.lonelycountry.springboot_03_hibernate.po;

import lombok.Data;

import javax.persistence.*;

/**
 * @author zhuqiwei
 * 2018/6/29.
 */
@Data
@Entity
@Table(name = "user")
public class User {
    /**
     * id
     */
    @Id
    private Long id;

    /**
     * 登录名
     */
    @Column(name = "LOGIN_NAME")
    private String loginName;

    /**
     * 密码
     */
    @Column(name = "PASSWORD")
    private String password;
}
复制代码
(2)、User表

2、构建Dao层

package com.lonelycountry.springboot_03_hibernate.dao;

import com.lonelycountry.springboot_03_hibernate.po.User;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author zhuqiwei
 * 2018/6/29.
 */
public interface UserDao extends JpaRepository<User, Long> {
    /**
     * 获取用户信息
     * @param loginName 登录名
     * @return User
     */
    User findByLoginName(String loginName);
}
复制代码

说明:
第一步:继承JpaRepository<T, ID>接口。继承了这个接口就可以让你使用一些预制的方法,比如findById(ID id)、save(S entity)、deleteById(ID id)等等。
第二步:根据对应的语义生成对应的方法。这个比较有意思,比如你要查询名字为XX的类但是JpaRepository又没有提供这个接口,就可以使用语义法来编写接口,格式是findByName(String name),其中Name换成字段名(第一个字母大写)就可以了,具体可以查看JpaRepository 查询规范

3、构建controller层和service层

LoginServiceImpl

package com.lonelycountry.springboot_03_hibernate.service;

import com.lonelycountry.springboot_03_hibernate.dao.UserDao;
import com.lonelycountry.springboot_03_hibernate.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

/**
 * @author zhuqiwei
 * 2018/6/29.
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserDao userDao;

    @Override
    public User getUserMsg(String loginName) {
        return userDao.findByLoginName(loginName);
    }

    @Override
    public Optional<User> getUserMsg(Long id) {
        return userDao.findById(id);
    }

    @Override
    public void saveUserMsg(String loginName, String password) {
        User user = new User();
        user.setId(UUID.randomUUID().getMostSignificantBits());
        user.setLoginName(loginName);
        user.setPassword(password);
        userDao.save(user);
    }

    @Override
    public void updateUserMsg(Long id, String loginName, String password) {
        User user = new User();
        user.setId(id);
        user.setLoginName(loginName);
        user.setPassword(password);
        userDao.save(user);
    }

    @Override
    public void deleteUserMsg(Long id) {
        userDao.deleteById(id);
    }
}
复制代码
package com.lonelycountry.springboot_03_hibernate.controller;

import com.google.common.collect.Maps;
import com.lonelycountry.springboot_03_hibernate.po.User;
import com.lonelycountry.springboot_03_hibernate.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author zhuqiwei
 * 2018/6/29.
 */
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    HttpServletRequest request;

    @GetMapping("/msg/{loginName}")
    public User getUserMsg(@PathVariable String loginName) {
        User user = loginService.getUserMsg(loginName);
        return user;
    }

    @GetMapping("/msg2/{id}")
    public User getUserMsg(@PathVariable Long id) {
        User user = loginService.getUserMsg(id).isPresent() ? loginService.getUserMsg(id).get() : null;
        return user;
    }

    @PostMapping("/msg/{loginName}/{password}")
    public Map<String, Object> saveUserMsg(@PathVariable String loginName, @PathVariable String password) {
        loginService.saveUserMsg(loginName, password);
        Map<String, Object> result = Maps.newHashMap();
        result.put("stauts", "successed");
        return result;
    }

    @PutMapping("/msg/{id}/{loginName}/{password}")
    public Map<String, Object> updateUserMsg(@PathVariable Long id, @PathVariable String loginName, @PathVariable String password) {
        loginService.updateUserMsg(id, loginName, password);
        Map<String, Object> result = Maps.newHashMap();
        result.put("stauts", "successed");
        return result;
    }

    @DeleteMapping("/msg/{id}")
    public Map<String, Object> updateUserMsg(@PathVariable Long id) {
        loginService.deleteUserMsg(id);
        Map<String, Object> result = Maps.newHashMap();
        result.put("stauts", "successed");
        return result;
    }
}
复制代码

五、集成Druid连接池

1、增加pom依赖文件

<!-- druid连接池 -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-starter</artifactId>
	<version>1.1.10</version>
</dependency>
复制代码

2、增加配置文件

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 1
      min-idle: 3
      max-active: 20
      max-wait: 60000
      validation-query: select 'x'
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
复制代码

3、增加配置类

DruidConfig

package com.lonelycountry.springboot_03_hibernate.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhuqiwei
 * 2018/7/26.
 */
@Configuration
public class DruidConfig {
    @Bean
    public ServletRegistrationBean statViewServlet() {
        // 创建servlet注册实体
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),
                "/druid/*");
        // 设置ip白名单
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        // 设置ip黑名单,如果allow与deny共同存在时,deny优先于allow
        servletRegistrationBean.addInitParameter("deny", "192.168.0.1");
        // 设置控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        // 是否可以重置数据
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean statFilter() {
        // 创建过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        // 设置过滤器过滤路径
        filterRegistrationBean.addUrlPatterns("/*");
        // 忽略过滤的形式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
复制代码

六、启动工程

1、测试接口

2、druid控制台("http(s)://ip:port/druid")

可以看到各项数据

七、代码地址及参考文档

源代码

八、说明

本文为原创,转载请注明原处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值