Spring Boot學習——數據庫操作及事務管理


       本文講解使用Spring-Data-Jpa操作數據庫。

  JPA定義了一系列對象持久化的標准。

       一、在項目中使用Spring-Data-Jpa

              1. 配置文件application.properties中配置如下代碼:

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/dbstudent
    username: root
    password: ccvdp
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

             注:spring.jpa.ddl-auto的值如下:

                          a.create:每次加載hibernate時都會刪除上一次的生成的表,然后根據你的model類再重新來生成新表,哪怕兩次沒有任何改變也要這樣執行,這就是導致數據庫表                                數據丟失的一個重要原因
                          b.create-drop:每次加載hibernate時根據model類生成表,但是sessionFactory一關閉,表就自動刪除
                          c.update:最常用的屬性,第一次加載hibernate時根據model類會自動建立起表的結構(前提是先建立好數據庫),以后加載hibernate時根據model類自動更新表結                              構,即使表結構改變了但表中的行仍然存在不會刪除以前的行。要注意的是當部署到服務器后,表結構是不會被馬上建立起來的,是要等應用第一次運行起來后才                             會
                          d.validate:每次加載hibernate時,驗證創建數據庫表結構,只會和數據庫中的表進行比較,不會創建新表,但是會插入新值
                          e.none:沒有配置

              2. pom.xml添加如下依賴:

<!-- JPA依賴 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- mysql依賴 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

              3. 創建數據表實體類

package com.aston.reader.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Student {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private Integer age;

    public Student(){
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

                            啟動項目,會自動創建數據表。

              4. 創建Repository接口StudentRepository

package com.aston.reader.interfaces;

import com.aston.reader.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface StudentRepository extends JpaRepository<Student, Integer>{
    /**
     * 擴展,按年齡查詢
     * @param age
     * @return
     */
    public List<Student> findByAge( Integer age);
}

              5. 創建操作數據庫類

package com.aston.reader.controller;

import com.aston.reader.interfaces.StudentRepository;
import com.aston.reader.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class StudentController {
    @Autowired
    private StudentRepository studentRepository;

    /**
     * 查詢學生列表
     * @return
     */
    @GetMapping(value = "/students")
    public List<Student> getStudentList(){
        return studentRepository.findAll();
    }

    /**
     * 添加學生
     * @param name
     * @param age
     * @return
     */
    @PostMapping(value = "/addStudent")
    public Student addStudent( @RequestParam("name") String name, @RequestParam("age") Integer age){
        Student student = new Student();

        student.setAge( age);
        student.setName( name);

        return studentRepository.save( student);
    }

    /**
     * 根據ID查詢學生
     * @param id
     * @return
     */
    @GetMapping(value = "findStudent/{id}")
    public Student findById(@PathVariable("id") Integer id){
        return studentRepository.findOne(id);
    }

    /**
     * 根據ID更新student記錄
     * @param id
     * @param name
     * @param age
     * @return
     */
    @PutMapping(value = "/student/{id}")
    public Student updateStudent(@PathVariable("id") Integer id, @RequestParam("name") String name, @RequestParam("age") Integer age){
        Student student = new Student();

        student.setId( id);
        student.setName( name);
        student.setAge( age);

        return studentRepository.save( student);
    }

    /**
     * 根據ID刪除記錄
     * @param id
     */
    @DeleteMapping(value = "student/{id}")
    public void deleteStudent(@PathVariable("id") Integer id){
        studentRepository.delete(id);
    }

    /**
     * 擴展,按年齡查詢記錄
     * @param age
     * @return
     */
    @GetMapping(value = "/findByAge")
    public List<Student > findByAge(@RequestParam("age") Integer age){
        return studentRepository.findByAge( age);
    }
}

              二、注意

                            有一個擴展的操作。

              三、事務管理

                            涉及數據庫操作就必然會用到事務。事務指訪問並可能更新數據庫中各種數據項的一個程序執行單元(unit)。

                            Spring Boot的事務使用比較簡單,只需在方法上使用注解 @Transactional。代碼實例如下:

import javax.transaction.Transactional;

@Transactional
public void insertStudents(){
    Student student1 = new Student();
    student1.setName("zhangsan");
    student1.setAge(17);
    studentRepository.save(student1);

    Student student2 = new Student();
    student2.setName("lisi");
    //student2.setAge(111);
    studentRepository.save(student2);
}

                             在操作數據庫時要認真考慮事務的范圍。只有查詢的時候可以不需要加事務。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM