1. 程式人生 > >Spring Boot的數據訪問 之Spring Boot + jpa的demo

Spring Boot的數據訪問 之Spring Boot + jpa的demo

上架 pri pat result over factor ack getname http

1. 快速地創建一個項目,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>

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

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>


        <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>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  

2. 新建一個實體,這邊以Book對象為例,主要囊括了書店中書的一些信息

技術分享圖片

package com.example.demo.entity;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;

@Entity
public class Book implements Serializable {

    public static final long seriaVersionUID = 1L;
    
    @Id
    @GeneratedValue
    private long id;

    @Column(nullable=false,unique=true)
    private String name;

    @Column(nullable=false)
    private String author;

    @Column(nullable=false)
    private String ontime;

    @Column(nullable=false)
    private int number;

    @Column(nullable=false)
    private float price;

    @Column(nullable=false)
    private String createdt;
    @Column(nullable=false)
    private String updatedt;
    @Column(nullable=false)
    private String creatuid;
    @Column(nullable=false)
    private String updateuid;

    public long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getOntime() {
        return ontime;
    }

    public void setOntime(String ontime) {
        this.ontime = ontime;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public String getCreatedt() {
        return createdt;
    }

    public void setCreatedt(String createdt) {
        this.createdt = createdt;
    }

    public String getUpdatedt() {
        return updatedt;
    }

    public void setUpdatedt(String updatedt) {
        this.updatedt = updatedt;
    }

    public String getCreatuid() {
        return creatuid;
    }

    public void setCreatuid(String creatuid) {
        this.creatuid = creatuid;
    }

    public String getUpdateuid() {
        return updateuid;
    }

    public void setUpdateuid(String updateuid) {
        this.updateuid = updateuid;
    }

    protected Book(){super();};

    public Book(String name, String author, String ontime, int number, float price, String createdt, String updatedt, String creatuid, String updateuid) {
        this.name = name;
        this.author = author;
        this.ontime = ontime;
        this.number = number;
        this.price = price;
        this.createdt = createdt;
        this.updatedt = updatedt;
        this.creatuid = creatuid;
        this.updateuid = updateuid;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", author=‘" + author + ‘\‘‘ +
                ", ontime=‘" + ontime + ‘\‘‘ +
                ", number=" + number +
                ", price=" + price +
                ", createdt=‘" + createdt + ‘\‘‘ +
                ", updatedt=‘" + updatedt + ‘\‘‘ +
                ", creatuid=‘" + creatuid + ‘\‘‘ +
                ", updateuid=‘" + updateuid + ‘\‘‘ +
                ‘}‘;
    }
}

  

3. 新建一個BookRepository接口,且繼承JpaRepository

public interface BookRepository extends JpaRepository<Book, Long> {

    
}

  

4. 了解hibernate的ddl-auto四種模式和用途

# 服務端口
server.port=8083

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/spring
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.hibernate.ddl-auto=validate

 

spring.jpa.hibernate.ddl-auto = 可以是4中Value
create
create-drop
validate
update

技術分享圖片

Hibernate我們公司的正式項目中基本不用,原因是性能上不是很好,不知道其他公司使用起來如何?

hibernate在多線程下,拼接sql,知道數據庫有問題,卻很難定位到是哪一段sql。後來漸漸棄用。用mybaits了~

5. 添加controller進行新增數據

package com.example.demo.controller;


import com.example.demo.entity.Book;
import com.example.demo.entity.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class BookController {

    @Autowired
    private BookRepository bookRepository;


    @RequestMapping("/save")
    @ResponseBody
    public void save() {
        bookRepository.save(new Book("書名11", "作者", "上架時間", 100, 23, "創建時間", "更新時間", "創建uid", "更新uid"));
        bookRepository.save(new Book("書名12", "作者", "20001111", 100, 23, "19990111", "19990111", "3", "4"));
        bookRepository.save(new Book("西遊記10", "吳承恩", "19991211", 100, 20, "19991111", "19991111", "2", "3"));
    } }

  項目啟動起來,在瀏覽器中輸入 http://localhost:8083/save,查詢數據庫中,已經新增了三條記錄;

可以順帶測試下ddl-auto的四種值,是否有如同描述一般的作用

技術分享圖片

6. 再添加查詢方法,並在controller中進行查詢

package com.example.demo.entity;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findByAuthor(String author);
}

  再在BookRepository 中添加查找方法,根據作者查詢出符合的Book 列表

package com.example.demo.controller;

import com.example.demo.entity.Book;
import com.example.demo.entity.BookRepository;
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;

@RestController
public class BookController {

    @Autowired
    private BookRepository bookRepository;


    @RequestMapping("/save")
    public void save() {
        bookRepository.save(new Book("書名11", "作者", "上架時間", 100, 23, "創建時間", "更新時間", "創建uid", "更新uid"));
        bookRepository.save(new Book("書名12", "作者", "20001111", 100, 23, "19990111", "19990111", "3", "4"));
        bookRepository.save(new Book("西遊記10", "吳承恩", "19991211", 100, 20, "19991111", "19991111", "2", "3"));
    }

    @RequestMapping("/findByAuthor")
    public void findByAuthor() {
        List<Book> result = bookRepository.findByAuthor("作者");
        System.out.println("一共有多少條呢----" + result.size());
        for (Book book : result) {
            System.out.println(book);
        }
        System.out.println("================================");
    }
}

  保存,啟動新項目,在瀏覽器中輸入http://localhost:8083/findByAuthor,查看控制臺是否打印出Book信息

技術分享圖片

Spring Boot的數據訪問 之Spring Boot + jpa的demo