Spring data jpa是Spring使用jpa的組件墨叛。采用Hibernate實現(xiàn)jpa能力。但是比自行Spring和Hibernate整合使用方便很多尝盼。
引入組件
在pom.xml中加入組件吞滞,這里連接MySQL數(shù)據(jù)庫,所以引入mysql-connector-java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
創(chuàng)建模型
jpa講究的是面向對象的思維盾沫,降低了數(shù)據(jù)庫的可見性裁赠。它可以完全不去寫SQL語句完成對數(shù)據(jù)庫中數(shù)據(jù)的增刪改查操作。一個數(shù)據(jù)模型對應一個數(shù)據(jù)表赴精。我們對數(shù)據(jù)的操作關心對這個對象的業(yè)務過程组贺。
創(chuàng)建一個模型,名稱為Account祖娘。這個對象是用于描述系統(tǒng)中的賬戶失尖。創(chuàng)建名稱為com.biboheart.demos.domain的package啊奄,在此package中新建類Account。如下:
package com.biboheart.demos.domain;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity // 表示這是一個jpa模型
@Table(name = "bh_account") // 表示對應數(shù)據(jù)表bh_account
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id; // ID
private String sn; // 賬戶編號
private String username; // 用戶名
private String mobile; // 手機號
private String password; // 密碼
private Long createTime; // 創(chuàng)建時間
}
創(chuàng)建接口
創(chuàng)建模型后掀潮,執(zhí)行數(shù)據(jù)增刪查改操作菇夸。spring data jpa提供了約定的方式來簡化使用。它約定仪吧,繼承JpaRepository的接口庄新,在接口中定義的函數(shù)名稱就可以執(zhí)行不同的數(shù)據(jù)操作。復雜的可以用注解來完成薯鼠。如findBySn函數(shù)择诈,就可以實現(xiàn)用戶sn匹配查找賬戶。通過這樣約定的情況下使用spring data jpa出皇,不需要實現(xiàn)這個接口羞芍。寫了這個接口,就可以將這個接口注入到業(yè)務中使用郊艘。
在com.biboheart.demos.repository中創(chuàng)建AccountRepository荷科。如下代碼:
package com.biboheart.demos.repository;
import com.biboheart.demos.domain.Account;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface AccountRepository extends JpaRepository<Account, Integer>, JpaSpecificationExecutor<Account> {
Account findBySn(String sn);
}
在業(yè)務代碼中如下方法注入,就可以通過accountRepository.findBySn(sn)查找匹配到sn的用戶纱注。
@Autowired
private AccountRepository accountRepository;
配置連接
這時候畏浆,jpa并不知道Account對應的是哪個數(shù)據(jù)庫的表。要配置數(shù)據(jù)庫連接狞贱。在application.yml中配置spring.datasource刻获,spring boot中項目中許多框架就可以自動得到數(shù)據(jù)庫的連接參數(shù)。配置spring.jpa設置spring data jpa的屬性瞎嬉。
server:
port: 80
spring:
profiles:
active: dev
resources:
static-locations: file:/usr/local/bhhello/static, classpath:/static/
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/bh_springbootdemo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
username: root
password: root
jpa:
database: MYSQL
database-platform: org.hibernate.dialect.MySQL5Dialect
show-sql: false
hibernate:
ddl-auto: update
properties:
hibernate:
format_sql: false
custom:
name: bhhello-app
測試連接
在com.biboheart.demos.service中創(chuàng)建接口AccountService缤灵,在com.biboheart.demos.service.impl中創(chuàng)建實現(xiàn)AccountServiceImpl土匀。代碼如下:
package com.biboheart.demos.service;
import com.biboheart.demos.domain.Account;
public interface AccountService {
/**
* 保存賬戶
* @param account 賬戶對像
* @return 保存后的賬戶對像歧杏,如果保存失敗返回null
*/
Account save(Account account);
/**
* 查詢賬戶
* @param sn 賬戶編號
* @return 查詢結果蛆封,賬戶對像
*/
Account load(String sn);
}
實現(xiàn)(這里未做容錯處理):
package com.biboheart.demos.service.impl;
import com.biboheart.brick.utils.CheckUtils;
import com.biboheart.demos.domain.Account;
import com.biboheart.demos.repository.AccountRepository;
import com.biboheart.demos.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.UUID;
@Service
public class AccountServiceImpl implements AccountService {
// 注入account數(shù)據(jù)庫訪問對象
@Autowired
private AccountRepository accountRepository;
@Override
public Account save(Account account) {
if (CheckUtils.isEmpty(account.getSn())) {
// 生成賬戶編號
String sn = UUID.randomUUID().toString().replace("-", "").toUpperCase();
while (null != accountRepository.findBySn(sn)) {
sn = UUID.randomUUID().toString().replace("-", "").toUpperCase();
}
account.setSn(sn);
}
account = accountRepository.save(account);
return account;
}
@Override
public Account load(String sn) {
Account account = accountRepository.findBySn(sn);
return account;
}
}
開放兩個API茬贵,實現(xiàn)創(chuàng)建賬戶與查詢賬戶的功能。在com.biboheart.demos.controller中創(chuàng)建AccountController類螟左。
package com.biboheart.demos.controller;
import com.biboheart.brick.model.BhResponseResult;
import com.biboheart.demos.domain.Account;
import com.biboheart.demos.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping(value = "/public/userapi/account/save", method = {RequestMethod.POST, RequestMethod.GET})
public BhResponseResult<?> save(Account account) {
account = accountService.save(account);
return new BhResponseResult<>(0, "success", account);
}
@RequestMapping(value = "/public/userapi/account/load", method = {RequestMethod.POST, RequestMethod.GET})
public BhResponseResult<?> load(String sn) {
Account account = accountService.load(sn);
return new BhResponseResult<>(0, "success", account);
}
}
為了方便測試钳吟,配置SecurityConfiguration,使"/public"開頭的api不需要安全認證坝茎。
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/", "/home", "/mobileCodeLogin", "/public/**").permitAll() // 這三個目錄不做安全控制
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")// 自定義的登錄頁面
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/");
http.addFilterBefore(mobileCodeAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
// @formatter:on
}
結尾
這章中厨喂,通過spring data jpa對數(shù)據(jù)庫進行創(chuàng)建表派阱,增加數(shù)據(jù),查詢數(shù)據(jù)的操作。從頭到尾沒有使用SQL語句橘原。除了配置文件中配置了數(shù)據(jù)庫連接參數(shù),業(yè)務過程與java程序的面向對象操作無異。