1. 程式人生 > >SpringBoot入門(三)--資料庫操作&&Spring-data-jpa的使用

SpringBoot入門(三)--資料庫操作&&Spring-data-jpa的使用

一、新增依賴

專案程式碼:https://github.com/ffzhihua/springbootdemo 

資料庫框架主要使用了sping-data-jpa

    <!--spring-data-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>

二、springboot的配置

1、application.yml檔案的配置

spring:
  profiles:
    active: dev

  #資料庫驅動等一些資訊
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/springboot
    username: root
    password: root

  #spring-data-jpa的配置
  jpa:
    hibernate:
      #設定自動建立資料庫
      #create:先刪除,再建立表,以前表的資料清除
      #update:不刪除以前的資料
      #create-drop:當應用停下來的時候刪除
      #none:預設什麼也不做
      #validate:先驗證實體類和表結構是否一致,不一致就會報錯
      ddl-auto: create
    #設定顯示執行的sql語句
    show-sql: true

 

2、設定實體類

User.java

package cn.buildworld.springbootdemo;

import org.springframework.web.bind.annotation.PathVariable;

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

/**
 * @Description:使用者類
 * @Author: zhihua
 * @Date: 2019/1/9
 */
@Entity
public class User {

    @Id
    @GeneratedValue
    private Long id;
    private String username;
    private int userage;


    public Long getId(){
        return id;
    }

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

    public String getUsername(){
        return username;
    }

    public void setUsername(String username){
        this.username = username;
    }

    public int getUserage(){
        return userage;
    }

    public void setUserage(int userage){
        this.userage = userage;
    }


}

3、設定dao層介面

UserRespository.java

package cn.buildworld.springbootdemo;

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

import java.util.List;

/**
 * @Description:dao層介面
 * @Author: zhihua
 * @Date: 2019/1/9
 */
public interface UserRespository extends JpaRepository<User,Long> {
    /**
     *
     * @param age
     * @return
     */
    public List<User> findByUserage(Integer age);
}

 

4、web層的控制器實現我們所需的功能(增刪改查)

UserController.java

package cn.buildworld.springbootdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Description:
 * @Author: zhihua
 * @Date: 2019/1/9
 */
@RestController
public class UserController {

    @Autowired
    private UserRespository userRespository;

    @GetMapping("getInfo")
    public List<User> getInfo() {

        List<User> all = userRespository.findAll();
        return all;
    }

    /**
     * POST方式
     *
     * @return
     */
    @PostMapping(value = "getInfo")
    public String getInfoByPost() {
        return "請使用get方式!";
    }

    @PostMapping(value = "adduser")
    public User addUser(@ModelAttribute User user) {
        userRespository.save(user);
        return user;
    }

    @GetMapping(value = "user/{id}")
    public User checkUser(@PathVariable("id") Long id) {
        return userRespository.findById(id).orElse(null);
    }

    @PutMapping("user/{id}")
    public User updateUser(@PathVariable("id") Long id, User user) {
        user.setId(id);
        userRespository.save(user);
        return userRespository.findById(id).orElse(null);

    }

    /**
     * DELETE方式刪除一個使用者
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "user/{id}")
    public List<User> deleteUser(@PathVariable("id") Long id) {
        userRespository.deleteById(id);
        return userRespository.findAll();
    }
    /**
     * 通過年齡來查詢使用者資訊
     * @param age
     * @return
     */
    @GetMapping(value = "user/age/{age}")
    public List<User> findUserByAge(@PathVariable("age")int age){
        return userRespository.findByUserage(age);
    }


}

5、事務

UserService.java

package cn.buildworld.springbootdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description:
 * @Author: zhihua
 * @Date: 2019/1/10
 */
@Service
public class UserService {
    @Autowired
    private UserRespository userRespository;

    @Transactional(rollbackFor = Exception.class)
    public void insertTwo(){


    }
}