SpringBoot05 數據操做01 -> JPA的基本使用、基本使用02

前提:css

  建立一個springboot項目html

  建立一個名爲springboottest的MySQL數據庫java

  

1 jar包準備

  jpa的jar包mysql

  mysql驅動的jar包web

  druid數據庫鏈接池的jar包spring

  lombok工具jar包sql

  注意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基礎配置詳解:點擊前往apache

druid配置詳解:點擊前往springboot

 

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);
    }

}
測試類
相關文章
相關標籤/搜索