前提:

  创建一个springboot项目

  创建一个名为springboottest的MySQL数据库

  

1 jar包准备

  jpa的jar包

  mysql驱动的jar包

  druid数据库连接池的jar包

  lombok工具jar包

  注意01: druid的jar包在都如时一定要指定版本,其它的spring boot项目会自动进行版本管理

<?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>cn.xiangxu</groupId><artifactId>springboot</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>springboot</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.8.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><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--数据库相关--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.19</version></dependency><!--工具--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

pom.xml

2 数据库连接池配置和JPA配置

spring:datasource:type: com.alibaba.druid.pool.DruidDataSource # 指定使用druid连接池driver-class-name: com.mysql.jdbc.Driverusername: rootpassword: 182838url: jdbc:mysql://127.0.0.1/springboottest?characterEncoding=utf-8&useSSL=false#最大活跃数maxActive: 20#初始化数量initialSize: 1#最大连接等待超时时间maxWait: 60000#打开PSCache,并且指定每个连接PSCache的大小poolPreparedStatements: truemaxPoolPreparedStatementPerConnectionSize: 20#通过connectionProperties属性来打开mergeSql功能;慢SQL记录#connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000minIdle: 1timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: select 1 from dualtestWhileIdle: truetestOnBorrow: falsetestOnReturn: false#配置监控统计拦截的filters,去掉后监控界面sql将无法统计,'wall'用于防火墙filters: stat, wall, log4jjpa:show-sql: truehibernate:ddl-auto: update
#      format-sql: true # TODO: 配置失败

连接池和JPA配置

package cn.xiangxu.springboot.baseConfig;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;/*** 配置DRUID访问的Sevlet和filter*/
@Configuration
public class DruidConfiguration {@Beanpublic ServletRegistrationBean statViewServlet(){//创建servlet注册实体ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");//设置ip白名单servletRegistrationBean.addInitParameter("allow","127.0.0.1");//设置ip黑名单,如果allow与deny共同存在时,deny优先于allowservletRegistrationBean.addInitParameter("deny","192.168.0.19");//设置控制台管理用户servletRegistrationBean.addInitParameter("loginUsername","wys");servletRegistrationBean.addInitParameter("loginPassword","123456");//是否可以重置数据servletRegistrationBean.addInitParameter("resetEnable","false");return servletRegistrationBean;}@Beanpublic FilterRegistrationBean statFilter(){//创建过滤器FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());//设置过滤器过滤路径filterRegistrationBean.addUrlPatterns("/*");//忽略过滤的形式filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");return filterRegistrationBean;}
}

druid的servlet和filter配置

jpa基础配置详解:点击前往

druid配置详解:点击前往

3 创建一个实体类

  实体类相关注解说明:点击前往

  技巧01:lombok的妙用

  注意01:使用lombok的坑 -> 即使导入了相关的jar包,lombok的注解在IDEA中时不会生效的,但是项目进行打包后就会生效 -> 解决办法

package cn.xiangxu.springboot.entity.dataObject;import lombok.Data;import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;@Entity
@Data
public class Girl {@Id@GeneratedValue@Column(name = "girlId")private Integer id;private Integer age;private String name;public Girl() {}public Girl(Integer age, String name) {this.age = age;this.name = name;}
}

实体类

4 创建一个与实体类对应的持久层接口

  注意01:该接口需要实现一个特定的父接口JpaRepository,继承了这个接口后就该接口就会自动被容器管理,无需再添加注解

chijge cn.xiangxu.springboot.repository;import cn.xiangxu.springboot.entity.dataObject.Girl;
import org.springframework.data.jpa.repository.JpaRepository;public interface GirlRepository extends JpaRepository<Girl, Integer> {}

持久层接口

5 创建一个服务层接口

  调用持久层对象的相应方法实现简单的增删改查操作

package cn.xiangxu.springboot.service;import cn.xiangxu.springboot.entity.dataObject.Girl;import java.util.List;public interface GirlService {Girl saveGirl(Girl girl);Girl findGirlOne(Integer id);List<Girl> finGirldAll();
}

服务层接口

package cn.xiangxu.springboot.service.serviceImpl;import cn.xiangxu.springboot.entity.dataObject.Girl;
import cn.xiangxu.springboot.repository.GirlRepository;
import cn.xiangxu.springboot.service.GirlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service("girlService")
public class GirlServiceImpl implements GirlService {@Autowiredprivate GirlRepository girlRepository;@Overridepublic Girl saveGirl(Girl girl) {return girlRepository.save(girl);}@Overridepublic Girl findGirlOne(Integer id) {return girlRepository.findOne(id);}@Overridepublic List<Girl> finGirldAll() {return girlRepository.findAll();}
}

服务层接口实现类

6 创建服务层测试类

package cn.xiangxu.springboot.service.serviceImpl;import cn.xiangxu.springboot.entity.dataObject.Girl;
import cn.xiangxu.springboot.service.GirlService;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.List;import static org.junit.Assert.*;@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j // 日志相关
public class GirlServiceImplTest {@Autowiredprivate GirlService girlService;@Testpublic void saveGirl() throws Exception {Girl girl = new Girl(25, "三少");Girl result = girlService.saveGirl(girl);log.info("【插入数据】");Assert.assertNotEquals(null, result);}@Testpublic void findGirlOne() throws Exception {Girl result = girlService.findGirlOne(1);log.info("【查询单个】");Assert.assertEquals(new Integer(1), result.getId());}@Testpublic void finGirldAll() throws Exception {List<Girl> girls = girlService.finGirldAll();log.info("查询列表");Assert.assertNotEquals(new Integer(0), new Integer(girls.size()));}}

服务层测试类

7 具体使用02

  说明:不使用数据库连接池,这里只是给出一些特殊的地方

  坑01:springboot版本升级后,实体类中的id字段必须根据数据库类型设定对应的默认主键值产生类型

package cn.xiangxu.jpa_demo01.domain.domain_do;import lombok.Data;import javax.persistence.*;/*** @author 王杨帅* @create 2018-08-12 15:01* @desc**/
@Entity
@Table(name = "student")
@Data
public class Student {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private String id;private String name;private Integer age;private String address;
}

Student.java

spring:datasource:url: jdbc:mysql://127.0.0.1/testdemo?characterEncoding=utf-8&useSSL=false
    username: rootpassword: 182838jpa:properties:hibernate:format_sql: trueshow_sql: true

配置类

package cn.xiangxu.jpa_demo01.repository;import cn.xiangxu.jpa_demo01.domain.domain_do.Student;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.List;import static org.junit.Assert.*;@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentRepositoryTest {@Autowiredprivate StudentRepository studentRepository;@Testpublic void findAll() {List<Student> all = studentRepository.findAll();Assert.assertTrue(all.size() > 0);}}

测试类

转载于:https://www.cnblogs.com/NeverCtrl-C/p/7904680.html

SpringBoot05 数据操作01 - JPA的基本使用、基本使用02相关推荐

  1. Spring Boot + JPA +MySQL 数据操作及示例环境搭建(自动建表)

    JPA 是Java官方提供的数据持久的统一API , 是一个接口标准,并没有具体实现. JPA的实现常见的有: Hibernate TopLink (Eclipse Link) Spring Boot ...

  2. 文件操作01 - 零基础入门学习C语言60

    第十一章:文件操作01 让编程改变世界 Change the world by program C文件概述 所谓"文件"是指一组相关数据的有序集合.这个数据集有一个名称,叫做文件名 ...

  3. MySQl的库操作、表操作和数据操作

    一.库操作 1.1库的增删改查 (1)系统数据库: performance_schema:用来收集数据库服务器的性能参数,记录处理查询时发生的各种事件.锁等现象 mysql:授权库,主要存储系统用户的 ...

  4. datagrid出现相同两组数据_stata 数据操作基础知识:以一篇论文数据操作为例

    stata 数据操作基础知识:以一篇论文数据操作为例 上节回顾及问题 统计学学习大图景 数据描述 分位数回归 存在的问题: 1.学了就要多使用,哪怕生搬硬套也要多用 2.时间序列的方法,大家可以操作, ...

  5. (d2l-ai/d2l-zh)《动手学深度学习》pytorch 笔记(2)前言(介绍各种机器学习问题)以及数据操作预备知识Ⅰ

    开源项目地址:d2l-ai/d2l-zh 教材官网:https://zh.d2l.ai/ 书介绍:https://zh-v2.d2l.ai/ 笔记基于2021年7月26日发布的版本,书及代码下载地址在 ...

  6. 【ARM】数据操作指令(下)

    00. 目录 文章目录 00. 目录 01. 数据操作指令概述 02. RSC指令 03. TST测试指令 04. TEQ指令 05. CMP 指令 06. CMN 指令 07. ORR 指令 08. ...

  7. 【ARM】数据操作指令(上)

    00. 目录 文章目录 00. 目录 01. 数据操作指令概述 02. MOV指令 03. MVN指令 04. AND指令 05. EOR 指令 06. SUB指令 07. RSB 指令 08. AD ...

  8. Pandas数据分析常用数据操作(3年总结)

    原创文章,转载请注明来源,谢谢 导入设置 import odps import numpy as np import pandas as pd import matplotlib as mpl imp ...

  9. MySQL 之binlog日志说明及利用binlog日志恢复数据操作记录

    众所周知,binlog日志对于mysql数据库来说是十分重要的.在数据丢失的紧急情况下,我们往往会想到用binlog日志功能进行数据恢复(定时全备份+binlog日志恢复增量数据部分),化险为夷! 一 ...

最新文章

  1. 输入vue ui没反应
  2. CentOS VMware 配置IP小结 静态 配置 桥接 NAT
  3. git 第三天 SSH免密码登录 2
  4. [[HOW TO]-ubuntu20.10安装openjrok指南
  5. 全球及中国矿棉板行业运营能力状况与十四五规模预测报告2022年
  6. Maven与IDEA结合
  7. IntelliJ IDEA使用(一)基本设置与类、方法模板设置
  8. Spring Boot————Web应用启动时自动执行ApplicationListener用法
  9. 以监控为核心 实现安防智能化全面兼容
  10. 学会这篇文章分享的知识,你就超过了90%的测试人
  11. 系统学习机器学习之正则化(一)
  12. 使用latex分割与合成PDF
  13. 人工智能 (特征数据提取)
  14. 如何将百度文库中不能复制的文字复制下来
  15. 2017年美国人工智能投资分析报告
  16. 计算机学硕考试时间,考研全年时间表!重要的23个时间点,都帮你整理好了
  17. APTHunter——Windows安全日志排查好帮手
  18. 设计模式大作业小型仓库管理系统【带数据库+文档】
  19. 荣耀手机两个android文件夹,华为手机文件管理中,这几个文件夹可以任意删除,其他的千万不要乱删!...
  20. 我在印尼工作的日子-基本环境

热门文章

  1. ecshop调用指定分类(包含子分类)下所有产品的评论信息
  2. 用Tcl定制Vivado设计实现流程
  3. char str[]与char *str的区别
  4. mysql不停止重启服务器_不停止MySQL服务增加从库的两种方式
  5. python数据拟合fit
  6. python 网络爬虫(一)
  7. 从源码分析DEARGUI之动态绘图的两种方法
  8. jbpm 6 vs activities 5评估(持续更新、亲测实际项目评估)
  9. spring-boot-mybatis
  10. 实战postfix邮件发送