1. 程式人生 > >Spring Boot JPA 連線資料庫

Spring Boot JPA 連線資料庫

本文將介紹如何在Spring Boot 工程中新增JPA作為持久化方式。

修改 pom.xml 依賴

與上一篇介紹的 jdbc 不同的是 spring-boot-starter-jdbc 修改為 spring-boot-starter-data-jpa 即可,當然資料庫驅動包也是不可少的,如下:

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

注意:如果你想JDBC和JPA可以一起使用,Spring Boot 是支援的,你只需要把JDBC和JPA的依賴都新增在pom.xml 中即可。無需其他特殊處理,有關JDBC的使用介紹請看上一篇 “

Spring-Boot JDBC 連線資料庫”。

修改屬性配置檔案

在屬性配置檔案中新增 JPA 相關屬性,注意這些並非必須,我們如果只新增dataSource 的 url\username\password\driver-class-name 也可以正常使用,有關JPA的其他配置都是可選的。

spring.jpa.database=
spring.jpa.show-sql=
spring.jpa.properties=
spring.jpa.generate-ddl=
spring.jpa.open-in-view=
spring.jpa.database-platform=
spring.jpa
.hibernate.ddl-auto= spring.data.jpa.repositories.enabled= spring.jpa.hibernate.naming-strategy=

熟悉JPA的根據名字應基本知道這些分別的作用了。

傳統上,JPA實體類在persistence.xml檔案中指定的。使用Spring Boot,這個檔案是沒有必要的,因為它使用“實體掃描”,預設情況下主配置 @EnableAutoConfiguration 或 @SpringBootApplication 下面的所有包都將會被掃描。任何使用註解 @Entity, @Embeddable 或 @MappedSuperclass 的類都將被管理。

Java程式碼例項

  • 一個介面
  • 一個Controller

我們建立一個介面 IScoreDao.java ,然後我們繼承框架為我們提供好的介面 Repository 或 CrudRepository (CrudRepository 繼承自 Repository),其中為我們提供了對資料庫的基本操作方法。

package org.springboot.sample.dao;

import java.util.List;

import javax.transaction.Transactional;

import org.springboot.sample.entity.Score;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

public interface IScoreDao extends CrudRepository<Score, Integer> {

    @Transactional
    @Modifying
    @Query("update Score t set t.score = :score where t.id = :id")
    int updateScoreById(@Param("score") float score, @Param("id") int id);

    @Query("select t from Score t ")
    List<Score> getList();

}

注意,如果你其中使用了修改、新增、刪除操作,則必須要在介面上面或者對應的方法上面新增 @Transactional 註解,否則會丟擲異常。

實體類 Score.java

package org.springboot.sample.entity;

import java.io.Serializable;
import java.util.Date;

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

/**
 * 成績
 *
 * @author 單紅宇(365384722)
 * @myblog http://blog.csdn.net/catoop/
 * @create 2016年1月12日
 */
@Entity
@Table(name = "score")
public class Score implements Serializable {

    private static final long serialVersionUID = 8127035730921338189L;

    @Id
    @GeneratedValue
    private int id;

    @Column(nullable = false, name="STUDENTID") // 這裡說一下,我使用指定資料庫列的時候,使用小寫會不起作用,修改為大寫便正常了。不知道為何,如果遇到一樣問題的可以嘗試下。
    private int stuId;

    @Column(nullable = false, name="SUBJECTNAME")
    private String subjectName;

    @Column(nullable = false)
    private float score;

    @Column(nullable = false, name="EXAMTIME")
    private Date examTime; 

    // 省去get、set 方法(佔用文章空間)

}

ScoreController.java

package org.springboot.sample.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springboot.sample.dao.IScoreDao;
import org.springboot.sample.entity.Score;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/score")
public class ScoreController {

    private static final Logger logger = LoggerFactory.getLogger(ScoreController.class);

    @Autowired
    private IScoreDao scoreService;

    @RequestMapping("/scoreList")
    public List<Score> getScoreList(){
        logger.info("從資料庫讀取Score集合");
        // 測試更新資料庫
        logger.info("更新的行數:" + scoreService.updateScoreById(88.8f, 2));
        scoreService.delete(23);

        return scoreService.getList();
    }
}

最後要說明的是,Spring 會自動為我們繼承CrudRepository介面的介面建立實現類。我們只需要在使用的時候直接使用註解 @Autowired 注入即可(IScoreDao 介面上也沒有必要增加 @Component 、 @Repository 等註解)。
還有,我這裡為了簡單起見,直接將操作資料庫的在Controller中使用,實際專案中,是不建議這樣做的,IScoreDao 的所屬角色是資料庫持久,我們還應當有 Service(如ScoreService) 來呼叫 IScoreDao 的方法,然後在Controller 中呼叫 Service 中的方法。原因是因為,我們資料庫訪問層,都是介面定義方法,上面註解注入SQL和引數,沒有具體的程式碼邏輯處理。如果我們想在執行SQL之前或之後執行邏輯處理,只能在 Service 中或者Controller(不建議)中。
我們嚴格按照這種方式去做(持久層只與SQL有關,通過介面定義無邏輯處理),這樣才是徹徹底底的持久層。越嚴格的規範制度,在某種程度上來說其實越有利於程式碼的管理和專案程式碼的迭代發展。

當然,如果你實在想要實現自己的 class 實現類,下面會附上一個例項程式碼,在此之前,我們先看一個圖片:
這裡寫圖片描述

這個圖是Spring 使用動態代理建立的介面例項,可以看出,其使用的是 SimpleJpaRepository 類,所以如果我們實現自己的 Repository ,可以擴充套件 SimpleJpaRepository 並 實現自己的 factory-class 入手,這裡不做詳解。注意凡事實現 Repository 介面的實現類都不需要新增 @Repository 註解,否則你會遇到問題。

本文介紹JPA 相比上一篇關於JDBC 的介紹增加的檔案工程截圖為:
工程結構截圖

熟悉其中一種持久資料的方法後,其他類似的都大同小異。