Spring JPA資料庫連線MySQL

oneslide發表於2018-04-03

實驗環境:

  1. 構建工具:Maven
  2. JDK:1.8+
  3. 框架:spring boot
  4. ORM框架:hibernate

MySQL資料庫需要配置檔案和maven依賴注入

資料庫配置檔案:

src/main/resources

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

第四個配置通常不是必須的,Spring-boot可以通過URL判斷出要連線的資料庫產品。

Maven的依賴注入

 <!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        
        <!-- Use MySQL Connector-J -->
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

JPA是java persistance API的簡稱,Spring Boot的JPA依賴包含了Hibernate的內建支援。

關於JPA和Hibernate的解釋(引用自:Java Persistance with Hibernate)

JPA and query languages: HQL vs. JPQL Before JPA existed (and even today, in some documentation), the query language in Hibernate was called HQL. The differences between JPQL and HQL are insignificant now. Whenever you provide a query string to any query interface in Hibernate, either with the EntityManager or Session, it’s a JPQL/HQL string. The same engine parses the query internally. The fundamental syntax and semantics are the same, although Hibernate, as always, supports some special constructs that aren’t standardized in JPA. We’ll tell you when a particular keyword or clause in an example only works in Hibernate. To simplify your life, think JPQL whenever you see HQL

資料庫實體類

資料庫實體類通常是必須的,因為它是Java應用運算元據的基本結構;關於實體的一些配置我這裡不予贅述。請參考Java 的POJO標準。不過對於Hibernate對於實體的管理我要整理一下知識體系。

實體類(Entity)是Hibernate查詢物件-Query操作的物件,任何複雜的查詢都應該基於Entity,正因如此,Hibernate才稱之為ORM(物件關係對映框架)

你可能會有如此程式碼,操作一些簡單的SQL語句:

import org.springframework.data.repository.CrudRepository;

import hello.User;

// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete

public interface UserRepository extends jpaRepository<User, Long> {

}

但是如何定義一些複雜的查詢方法呢?
Spring-Boot可以使用註解@Query,來執行一些複雜的查詢,你可以在UserRepository中書寫一個複雜的查詢方法:

@Query("Complex HQL')
public User UserWithComplexFilter(User user){

   //do something with HQL(Hibernate Query Language)
}

HQL具有很多種查詢方法和基於資料庫通用技術的封裝,包括基於規則查詢(Query by Creteria),分頁還有防止SQL隱碼攻擊的引數繫結技術以及外部配置Query來簡化和統一管理查詢的技術。我將會在下面整理。

相關文章