57.SpringBoot學習筆記--SpringData-整合SpringDataJPA

SpringData JPA 簡介

在這裏插入圖片描述
參考:

Java Persistence API 2.0 FINAL 官方文檔.pdf

整合 SpringData JPA

pom.xml

<?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 https://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.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>demo.yangxu</groupId>
    <artifactId>springboot-05-data-jpa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-05-data-jpa</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-jdbc</artifactId>
        </dependency>
        <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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

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

</project>

JPA: ORM(Object Relational Mapping)

1、編寫一個實體類(Bean)和數據表進行映射,並且配置好映射關係

demo.yangxu.springboot.entity.User

package demo.yangxu.springboot.entity;

import javax.persistence.*;

//使用JPA註解配置映射關係
@Entity //告訴JPA這是一個實體類(和數據表映射的類)
@Table(name = "tbl_user") //@Table來指定和哪個數據表對應;如果省略默認表名就是user;
public class User {
    
    @Id //這是一個主鍵
    @GeneratedValue(strategy = GenerationType.IDENTITY) //自增主鍵
    private Integer id;
    
    @Column(name = "last_name",length = 50) //這是和數據表對應的一個列
    private String lastName;
    
    @Column //省略默認列名就是屬性名
    private String email;

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

2、編寫一個 Dao 接口來操作實體類對應的數據表(Repository)

demo.yangxu.springboot.repository.UserRepository

package demo.yangxu.springboot.repository;

import demo.yangxu.springboot.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

//繼承JpaRepository來完成對數據庫的操作
public interface UserRepository extends JpaRepository<User,Integer> {
}

3、基本的配置 JpaProperties

application.yml

spring:
  datasource:
    url: jdbc:mysql://192.168.25.157/jpa
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      #     更新或者創建數據表結構
      ddl-auto: update
    #    控制檯顯示SQL
    show-sql: true

4、編寫 Controller 進行測試

demo.yangxu.springboot.controller.UserController

package demo.yangxu.springboot.controller;

import demo.yangxu.springboot.entity.User;
import demo.yangxu.springboot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable("id") Integer id){
        User user = userRepository.findById(id).orElse(null);
        return user;
    }

    @GetMapping("/user")
    public User insertUser(User user){
        User save = userRepository.save(user);
        return save;
    }
}

啓動控制檯後可以看到自動生成的建表語句:

Hibernate: create table tbl_user (id integer not null auto_increment, email varchar(255), last_name varchar(50), primary key (id)) engine=InnoDB

可以訪問以下網址測試:

http://localhost:8080/user?lastName=AA&[email protected]
http://localhost:8080/user/1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章