Spring Data JPA學習(一)之環境搭建

来源:https://www.cnblogs.com/bulesnail95/archive/2017/12/26/8119855.html
-Advertisement-
Play Games

Spring Data JPA是依附於Spring Boot的,學習Spring Data JPA之前得先把Spring Boot的環境搭建起來。 先附上一個Spring Data JPA的官方鏈接:https://docs.spring.io/spring-data/jpa/docs/curren ...


Spring Data JPA是依附於Spring Boot的,學習Spring Data JPA之前得先把Spring Boot的環境搭建起來。

先附上一個Spring Data JPA的官方鏈接:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

以下學習自:https://segmentfault.com/a/1190000006717969 Spring Data JPA 多數據源+異構資料庫實踐

1.建立一個maven項目,在pom.xml中添加依賴:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>


<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> </parent> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</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-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency>
</dependencies>
<build> <finalName>jpa</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins>
</build>

說明:

(1)spring-boot-devtools 是用於當修改了Java文件時,伺服器重新啟動編譯。

(2)spring-boot-starter-test是用於進行單元測試。

(3)spring-boot-starter-data-jpa是用於支持JPA。

保存pom.xml文件之後會自動下載jar包。如果在下載過程中因為某些原因中斷,可能會導致jar下載不完全,到jar包的存放位置將相應的jar刪除,再maven-->update project下載。

 

2.連接資料庫。在src/main/resources下建立application.yml文件,內容如下:

spring:
  datasource:
    terminal:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/terminal?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: xxxx
  jpa:
    show-sql: true
    database-platform: org.hibernate.dialect.MySQL5Dialect
    hibernate:
      ddl-auto: update
註意:在":"之後需要加一個空格。上面的terminal是連接的名稱。在url後面內容加了一個useSSL=false,如果不加,會出現下麵這個報錯:
Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

這裡選擇的JPA實現是Hibernate。

 

3.指定使用的資料庫連接和事務管理

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef="terminalEntityManagerFactory",
        transactionManagerRef="terminalTransactionManager",basePackages= { "gdut.ff.terminal"})
public class DataSourceConfiguration {
    
    @Autowired
    private JpaProperties jpaProperties;
    
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.terminal")
    public DataSource terminalDataSource(){
        return DataSourceBuilder.create().build();
    }
    
    @Bean(name = "terminalEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean terminalEntityManagerFactory(EntityManagerFactoryBuilder builder){
        LocalContainerEntityManagerFactoryBean em = builder.dataSource(terminalDataSource())
                                                           .packages("gdut.ff.terminal")
                                                           .persistenceUnit("terminal")
                                                           .properties(getVendorProperties(terminalDataSource()))
                                                           .build();
        return em;
    }
    
    @Primary
    @Bean(name = "entityManagerTerminal")
    public EntityManager entityManagerDefault(EntityManagerFactoryBuilder builder) {
        return terminalEntityManagerFactory(builder).getObject().createEntityManager();
    }
    
    private Map<String, String> getVendorProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }
    
    @Bean(name = "terminalTransactionManager")
    @Primary
    PlatformTransactionManager terminalTransactionManager(EntityManagerFactoryBuilder builder){
        return new JpaTransactionManager(terminalEntityManagerFactory(builder).getObject());
    }

}

註意:

(1)entityManagerFactoryRef="terminalEntityManagerFactory"要與LocalContainerEntityManagerFactoryBean註冊的@Bean(name = "terminalEntityManagerFactory")名稱相同。

(2)transactionManagerRef="terminalTransactionManager"要與new JpaTransactionManager()註冊的@Bean(name = "terminalTransactionManager")名稱一致。

(3)basePackages= { "gdut.ff.terminal"}表示這個數據源作用在哪些包。也可以寫做basePackages={"gdut.ff.terminal.**"},但是不能寫做basePackages={"gdut.ff.terminal.*"}

(4)@Primary表示預設。

(5)@ConfigurationProperties(prefix = "spring.datasource.terminal")表示使用的數據源的首碼是"spring.datasource.terminal"。

(6)貼一下我的包圖:

 

 4.建立一個實體Bean和對應的Dao介面

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface TerminalMachineRepository extends CrudRepository<TerminalMachine,String>{

    List<TerminalMachine> findByName(String name);
}

CrudRepository<>里的是Bea實體和對應的主鍵類型。這裡還可以繼承其他的Repository介面,如JpaRepository和PagingAndSortingRepository等等。

 

5.設置啟動類App.class

package gdut.ff.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({"gdut.ff.terminal.**","gdut.ff.config.**"})
public class App {

    public static void main(String[] args) throws Exception {
        
        SpringApplication.run(App.class, args);
        
    }
}

啟動類App.class啟動,掃描包gdut.ff.terminal和gdut.ff.config下的類

 

6.做一個單元測試

import java.util.Iterator;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import gdut.ff.config.App;

@RunWith(SpringRunner.class)
@SpringBootTest(classes=App.class)
public class TestTerminalMachine {
    
    @Autowired
    private TerminalMachineRepository terminalMachineRepository;
    
    @Test
    public void testFindAll(){
        Iterable<TerminalMachine> list = terminalMachineRepository.findAll();
        Iterator<TerminalMachine> iterator = list.iterator();
        while(iterator.hasNext()){
            TerminalMachine machine = iterator.next();
            System.out.println(machine.getName());
        }
    }

}

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 反射 一.獲得Class文件對象的三種方式(返回值都是Class類的對象) 1.通過類名調用class()獲得。 格式:類名.class(); 2.通過對象調用getClass()方法獲得; 格式:對象名.getClass(); 3.通過Class類的靜態方法forName()獲得 格式:Class ...
  • c3p0-0.9.2.1 jar包和mchange-commons-java-0.2.3.4 jar 包 下載地址: https://pan.baidu.com/s/1jHDiR7g 密碼 tyek ...
  • 環境:python3.6 目的:根據列表 中的字元串導入對應模塊 僅筆記,並知道有什麼實際用處 ...
  • ##閉包 :內部函數,在外部調用不在他函數範圍的變數 def outer(): x=10 def inner(): print(x) return inner #outer()() f=outer() f() 這裡inner就是一個閉包,閉包=內部函數+環境,這裡環境是x=10。閉包是為瞭解釋調用不 ...
  • node-schedule每次都是通過新建一個scheduleJob對象來執行具體方法。 時間數值按下表表示 指定時間有兩種方式1 字元串指定 *之間一定要加空格,否則不執行 每到秒數為4的倍數時執行 在秒位*後加/4 和後面的*之間要有空格schedule.scheduleJob('*/4 * * ...
  • Infi-chu: http://www.cnblogs.com/Infi-chu/ 模塊:filecmp 安裝:Python版本大於等於2.3預設自帶 功能:實現文件、目錄、遍歷子目錄的差異 常用方法: 1.單文件對比(cmp): 2.多文件對比(cmpfiles): 3.目錄對比(dircmp) ...
  • Description 給你一棵TREE,以及這棵樹上邊的距離.問有多少對點它們兩者間的距離小於等於K Input N(n<=40000) 接下來n-1行邊描述管道,按照題目中寫的輸入 接下來是k Output 一行,有多少對點之間的距離小於等於k Sample Input 7 1 6 13 6 3 ...
  • Zookerper在Linux上的安裝 最近在項目的時候,遇到一些linux的相關安裝,雖然不難,但是步驟不少,一不小心就會出錯,這樣去找錯誤費時費力,所以一般都是需要重新再來,實在是讓人頭疼,所以這裡做個總結,為需要的朋友留下一個參考,也給自己加深一下印象。 先來說一下zookeeper的安裝 要 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...