zoukankan      html  css  js  c++  java
  • SpringBoot05 数据操作01 -> JPA的基本使用、基本使用02

    前提:

      创建一个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.Driver
        username: root
        password: 182838
        url: jdbc:mysql://127.0.0.1/springboottest?characterEncoding=utf-8&useSSL=false
    
        #最大活跃数
        maxActive: 20
        #初始化数量
        initialSize: 1
        #最大连接等待超时时间
        maxWait: 60000
        #打开PSCache,并且指定每个连接PSCache的大小
        poolPreparedStatements: true
        maxPoolPreparedStatementPerConnectionSize: 20
        #通过connectionProperties属性来打开mergeSql功能;慢SQL记录
        #connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 1 from dual
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        #配置监控统计拦截的filters,去掉后监控界面sql将无法统计,'wall'用于防火墙
        filters: stat, wall, log4j
    
      jpa:
        show-sql: true
        hibernate:
          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 {
    
        @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.19");
            //设置控制台管理用户
            servletRegistrationBean.addInitParameter("loginUsername","wys");
            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;
        }
    }
    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 {
        @Autowired
        private GirlRepository girlRepository;
    
        @Override
        public Girl saveGirl(Girl girl) {
            return girlRepository.save(girl);
        }
    
        @Override
        public Girl findGirlOne(Integer id) {
            return girlRepository.findOne(id);
        }
    
        @Override
        public 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 {
    
        @Autowired
        private GirlService girlService;
    
        @Test
        public void saveGirl() throws Exception {
            Girl girl = new Girl(25, "三少");
            Girl result = girlService.saveGirl(girl);
            log.info("【插入数据】");
            Assert.assertNotEquals(null, result);
        }
    
        @Test
        public void findGirlOne() throws Exception {
            Girl result = girlService.findGirlOne(1);
            log.info("【查询单个】");
            Assert.assertEquals(new Integer(1), result.getId());
        }
    
        @Test
        public 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: root
        password: 182838
    
    
      jpa:
        properties:
          hibernate:
            format_sql: true
            show_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 {
    
        @Autowired
        private StudentRepository studentRepository;
    
        @Test
        public void findAll() {
            List<Student> all = studentRepository.findAll();
            Assert.assertTrue(all.size() > 0);
        }
    
    }
    测试类
  • 相关阅读:
    MySQL插入数据获得自动增长的ID
    C#解决“System.Threading.ThreadStateException:“在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。 只有将调试程序附加到该进程才会引发此异常”的异常
    C# 关闭当前窗体的时候打开另一个窗口
    C# WinForm中关闭指定的窗体
    MySQL 8.0 版本修改字符编码
    微信支付API v3接口使用应用篇
    Linux Tomcat安装篇(daemon运行,开机自启动)
    Linux nginx安装篇
    SpringCloud系列之Nacos+Dubbo+Seata应用篇
    SpringCloud系列之Nacos+Dubbo应用篇
  • 原文地址:https://www.cnblogs.com/NeverCtrl-C/p/7904680.html
Copyright © 2011-2022 走看看