初入SpringBoot整合Spring-Data-JPA學習
什麼是Spring-Data-JPA
說到Spring-Data-JPA就要先了解一下JPA是什麼?
JPA:Java Persistence API(java持久層API),JPA誕生的緣由是為了整合第三方ORM框架,建立一種標準的方式,百度百科說是JDK為了實現ORM的天下歸一,只是目前還沒能完全實現。在spring-data-jpa沒有出來之前,在ORM框架中,hibernate是與JPA整合較為良好的框架之一,我們可以認為JPA是標準,是規範,是介面,hibernate是對它的實現。
Spring-Data-JPA是什麼?
spring所做的並不只限於IOC容器或是AOP,對於持久化之部分也誕生出了越來越多的工具,於是就有了sping-data-xxx等一系列的包。如:sping-data-redis,spring-data-mongoDB,spring-data-template。而spring-data-jpa就是spring對於JPA進行的整合,並提供的又一個包。
SpringBoot整合Spring-Data-JPA
1.新增依賴關係 在pom中新增對於spring-data-jpa和mysql的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId> mysql-connector-java</artifactId>
</dependency>
2.編寫實體類 這裡只是簡單的例子,所以只有3個欄位,當專案執行後,會根據對應的欄位自動生成資料庫表結構
package com.wrp.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence. Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
//標識這個實體類是一個JPA實體,告訴JPA在程式執行的時候記得生成這個實體類所對應的表
@Entity
//自定義設定這個實體類在資料庫所對應的表名
@Table
public class UserAccount implements Serializable {
private static final long serialVersionUID = -8324350334397656866L;
// 把類裡所在的變數設定成主鍵
@Id
// 設定主鍵生成策略,這種方式依賴於具體的資料庫,如果資料庫不支援自增主鍵,那麼這個型別是沒法用的
@GeneratedValue(generator = "uuid")
// 自定義生成策略,配合@GeneratedValue一起使用,name需要和@GeneratedValue中的generato一直,strategy表示生成的策略,總共有14種
@GenericGenerator(name = "uuid", strategy = "uuid")
@Column(length = 32)
private String id;
// 對欄位進行個性化設定name = "自定義欄位名",length = "自定義長度",nullable =
// "是否可以空,false表示不能為null",unique = "是否唯一"
@Column(length = 100, unique = false, nullable = false)
private String userName;
@Column(length = 100, unique = false, nullable = false)
private String password;
public String getId() {
return id;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public void setId(String id) {
this.id = id;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
}
3.編寫控制層Controller
package com.wrp.web;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.wrp.domain.UserAccount;
import com.wrp.service.UserAccountService;
@RestController
@RequestMapping("/userAccount")
public class UserAccountController {
@Autowired
UserAccountService userAccountService;
@RequestMapping(value = "/findList", method = RequestMethod.GET)
public JSONObject findList() {
JSONObject jsonObject = new JSONObject();
List<UserAccount> userAccountList = userAccountService.findList();
jsonObject.put("userAccountList", userAccountList);
return jsonObject;
}
@RequestMapping(value = "/{id}")
public JSONObject getUserAccountById(@PathVariable String id) {
JSONObject jsonObject = new JSONObject();
UserAccount userAccount = userAccountService.getUserAccountById(id);
jsonObject.put("userAccount", userAccount);
return jsonObject;
}
@RequestMapping(value = "/login")
public JSONObject login(@RequestParam String userName, @RequestParam String password) {
JSONObject jsonObject = new JSONObject();
UserAccount userAccount = userAccountService.getByUserNameAndPassword(userName, password);
jsonObject.put("userAccount", userAccount);
return jsonObject;
}
@RequestMapping(method = RequestMethod.POST)
public JSONObject add(@RequestBody UserAccount userAccount) {
JSONObject jsonObject = new JSONObject();
if(userAccountService.addUserAccount(userAccount)) {
jsonObject.put("msg", "新增成功");
}else {
jsonObject.put("msg", "失敗");
}
return jsonObject;
}
}
4.編寫服務層和服務實現層 service層
package com.wrp.service;
import java.util.List;
import com.wrp.domain.UserAccount;
public interface UserAccountService {
/**
* 查詢所有
* @param serachMap
* @return
*/
List<UserAccount> findList();
/**
* 根據id查詢
* @param id
* @return
*/
UserAccount getUserAccountById(String id);
/**
* 通過userName和password查詢
* @param userName
* @param password
* @return
*/
UserAccount getByUserNameAndPassword(String userName, String password);
/**
* 新增
* @param userAccount
* @return
*/
boolean addUserAccount(UserAccount userAccount);
}
service實現層
package com.wrp.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wrp.dao.UserAccountDao;
import com.wrp.domain.UserAccount;
import com.wrp.service.UserAccountService;
@Service
public class UserAccountServiceImpl implements UserAccountService {
@Autowired
UserAccountDao userAccountDao;
public List<UserAccount> findList() {
return userAccountDao.findAll();
}
public UserAccount getUserAccountById(String id) {
return userAccountDao.getById(id);
}
public UserAccount getByUserNameAndPassword(String userName, String password) {
return userAccountDao.getByUserNameAndPassword(userName, password);
}
public boolean addUserAccount(UserAccount userAccount) {
UserAccount result = userAccountDao.save(userAccount);
if(result!=null) {
return true;
}
return false;
}
}
5.編寫DAO層 DAO層是一個介面,用於繼承Spring-Data-JPA中的JpaRepository(SpringDataJPA提供的簡單介面)和JpaSpecificationExecutor(SpringDataJPA提供的複雜介面),並且可以通過關鍵字(猶豫關鍵字比較多,這裡就不一一列舉,可自行百度)及動態SQL查詢(動態SQL支援原生SQL和JPQL兩種)
package com.wrp.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import com.wrp.domain.UserAccount;
public interface UserAccountDao extends JpaRepository<UserAccount, String>, JpaSpecificationExecutor<UserAccount> {
/**
*
* @param id
* @return
*/
UserAccount getById(String id);
/**
* 通過關鍵字And查詢
* @param userName
* @param password
* @return
*/
UserAccount getByUserNameAndPassword(String userName,String password);
/**
* nativeQuery:true代表使用原生SQL
* value:SQL語句
* @return
*/
@Query(nativeQuery=true,value="SELECT * FROM user_account")
List<UserAccount> getUserAccountList();
}
6.在application.properties檔案中配置資料來源
#服務埠
server.port=8762
#資料來源設定
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/wrp_demo?useUnicode\=true&characterEncoding\=UTF-8&serverTimezone\=UTC
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.initial-size=5
#指定必須保持連線的最小值
spring.datasource.min-idle=5
spring.datasource.max-idle=10
#指定連線池中最大的活躍連線數.
spring.datasource.max-active=50
#指定連線池等待連線返回的最大等待時間,毫秒單位.
spring.datasource.max-wait=10000
spring.datasource.validation-query=SELECT 1
#驗證連線的有效性
spring.datasource.test-while-idle=true
#空閒連接回收的時間間隔,與test-while-idle一起使用,設定5分鐘
spring.datasource.time-between-eviction-runs-millis=300000
#獲取連線時候驗證,會影響效能
spring.datasource.test-on-borrow=false
#在連線歸還到連線池時是否測試該連線
spring.datasource.test-on-return=false
#連線池空閒連線的有效時間 ,設定30分鐘
spring.datasource.min-evictable-idle-time-millis=1800000
# Specify the DBMS
spring.jpa.database=MYSQL
# Show or not log for each sql query
spring.jpa.show-sql=true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto=update
# Naming strategy
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.hibernate.dialect=org.hibernate.dialect.MySQLDialect
測試結果
1.執行啟動類後可以看到控制檯出會打印出建表的sql語句 在這裡插入圖片描述
2.通過瀏覽器呼叫介面 新增介面 執行程式後可以發現後臺生成了對應的新增SQL語句 資料庫添加了一條資料
呼叫finList介面進行檢視
結束語:
第一次寫相關的文章,如有不好的地方還請見諒,也可以一起探討