Spring?Boot深入學(xué)習(xí)數(shù)據(jù)訪問之Spring?Data?JPA與Hibernate的應(yīng)用
前言
Hibernate是一個開源的對象關(guān)系映射框架,它對JDBC及進(jìn)行了非常輕量級的對象封裝,它將POJO簡單的java對象與數(shù)據(jù)庫表建立映射關(guān)系,是一個全自動的ORM框架,Hibernate可以自動生成SQL語句自動執(zhí)行。
JPA是官方提出的Java持久化規(guī)范,JPA通過注解或XML描述對象一關(guān)系表的映射關(guān)系,并將內(nèi)存中的實體對象持久化到數(shù)據(jù)庫
Spring Data JPA通過提供基于JPA的Repository極大的簡化了JPA的寫法,在幾乎不寫實現(xiàn)的情況下,實現(xiàn)數(shù)據(jù)庫的訪問和操作,使用Spring Data JPA建立數(shù)據(jù)訪問層十分方便,只需要定義一個集成JapRepository的接口即可
Spring Boot的支持
可以在STS創(chuàng)建Spring Boot應(yīng)用時就選擇Spring Data JPA模塊依賴
如果在Maven項目中需要使用它,則可以在pom.xml文件中通過如下配置添加Spring Data JPA模塊依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
下面通過一個簡單的條件查詢實例來實戰(zhàn)
1:創(chuàng)建數(shù)據(jù)庫 此處不再贅述 有問題可以私信
2:修改pom.xml文件 添加mysql依賴
<?xml version="1.0" encoding="UTF-8"?> -<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"> <modelVersion>4.0.0</modelVersion> -<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.7.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.ch</groupId> <artifactId>ch6_1</artifactId> <version>0.0.1-SNAPSHOT</version> <name>ch6_1</name> <description>Demo project for Spring Boot</description> -<properties> <java.version>11</java.version> </properties> -<dependencies> -<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> -<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> -<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 添加MySQL依賴 --> -<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> <!-- MySQL8.x時,請使用8.x的連接器 --> </dependency> -<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> -<build> -<plugins> -<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
3:在application.properties文件中配置如下內(nèi)容
server.servlet.context-path=/ch6_1
###
##數(shù)據(jù)源信息配置
###
#數(shù)據(jù)庫地址
spring.datasource.url=jdbc:mysql://localhost:3306/springbootjpa?characterEncoding=utf8
#數(shù)據(jù)庫MySQL為8.x時,url為jdbc:mysql://localhost:3306/springbootjpa?useSSL=false&serverTimezone=Asia/Beijing&characterEncoding=utf-8
#數(shù)據(jù)庫用戶名
spring.datasource.username=root
#數(shù)據(jù)庫密碼
spring.datasource.password=root
#數(shù)據(jù)庫驅(qū)動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#數(shù)據(jù)庫MySQL為8.x時,驅(qū)動類為com.mysql.cj.jdbc.Driver
####
#JPA持久化配置
####
#指定數(shù)據(jù)庫類型
spring.jpa.database=MYSQL
#指定是否在日志中顯示SQL語句
spring.jpa.show-sql=true
#指定自動創(chuàng)建、更新數(shù)據(jù)庫表等配置,update表示如果數(shù)據(jù)庫中存在持久化類對應(yīng)的表就不創(chuàng)建,不存在就創(chuàng)建對應(yīng)的表
spring.jpa.hibernate.ddl-auto=update
#讓控制器輸出的JSON字符串格式更美觀
spring.jackson.serialization.indent-output=true
4:創(chuàng)建持久化實體類MyUser
創(chuàng)建名為com.ch.ch6_1entity的包 并在該包中創(chuàng)建名為MyUser的持久化實體類 部分代碼如下
package com.ch.ch6_1.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user_table")
/**
* 如果沒寫表名,默認(rèn)為類名的詞組
* (如MyUser類對應(yīng)的表名為my_user)
*/
public class MyUser implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;//主鍵
/**使用@Column注解,可以配置列相關(guān)屬性(列名,長度等),
* 可以省略,默認(rèn)為屬性名小寫
*/
private String uname;
private String usex;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUsex() {
return usex;
}
public void setUsex(String usex) {
this.usex = usex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}@Entity注解表明該實體類時一個與數(shù)據(jù)庫表映射的實體類
@Table表示實體類與哪個數(shù)據(jù)庫表映射
5:創(chuàng)建數(shù)據(jù)訪問層
創(chuàng)建名為com.ch.ch6_1.repository并在該包中創(chuàng)建名為UserRepository的接口 代碼如下
package com.ch.ch6_1.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.ch.ch6_1.entity.MyUser;
/**
* 這里不需要使用@Repository注解數(shù)據(jù)訪問層,
* 因為Spring Boot自動配置了JpaRepository
*/
public interface UserRepository extends JpaRepository<MyUser, Integer>{
public MyUser findByUname(String uname);
public List<MyUser> findByUnameLike(String uname);
}6:創(chuàng)建業(yè)務(wù)層
創(chuàng)建名為com.ch.ch6_1.service的包 并在該包中創(chuàng)建UserService接口和接口的實現(xiàn)類UserServiceImpl
接口代碼如下
package com.ch.ch6_1.service;
import java.util.List;
import com.ch.ch6_1.entity.MyUser;
public interface UserService {
public void saveAll();
public List<MyUser> findAll();
public MyUser findByUname(String uname);
public List<MyUser> findByUnameLike(String uname);
public MyUser getOne(int id);
}實現(xiàn)類部分代碼如下
package com.ch.ch6_1.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ch.ch6_1.entity.MyUser;
import com.ch.ch6_1.repository.UserRepository;
@Service
@Transactional
public class UserServiceImpl implements UserService{
@Autowired
private UserRepository userRepository;//依賴注入數(shù)據(jù)訪問層
@Override
public void saveAll() {
MyUser mu1 = new MyUser();
mu1.setUname("陳恒1");
mu1.setUsex("男");
mu1.setAge(88);
MyUser mu2 = new MyUser();
mu2.setUname("陳恒2");
mu2.setUsex("女");
eLike(String uname) {
return userRepository.findByUnameLike("%" + uname + "%");
}
@Override
public MyUser getOne(int id) {
//調(diào)用父接口中的方法getOne
return userRepository.getOne(id);
}
}7:創(chuàng)建控制器類UserTestController
創(chuàng)建名為com.ch.ch6_1.controller的包 并在該包中創(chuàng)建名為UserTestController的類 部分代碼如下
package com.ch.ch6_1.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ch.ch6_1.service.UserService;
@Controller
public class UserTestController {
@Autowired
private UserService userService;
@RequestMapping("/save")
@ResponseBody
public String save() {
userService.saveAll();
return "保存用戶成功!";
}
}
@RequestMapping("/findAll")
public String findAll(Model model){
model.addAttribute("title", "查詢所有用戶");
model.addAttribute("allUsers",userService.findAll());
return "showAll";
}
@RequestMapping("/findByUnameLike")
public String findByUnameLike(String uname, Model model){
model.addAttribute("title", "根據(jù)用戶名模糊查詢所有用戶");
model.addAttribute("allUsers",userService.findByUnameLike(uname));
return "showAll";
}
}8:整理腳本樣式靜態(tài)文件
JS腳本 CSS樣式 圖片等靜態(tài)文件默認(rèn)放在src/main/resourcex/static目錄下 有需求可以評論區(qū)留言找我要
9:創(chuàng)建View視圖頁面
創(chuàng)建視圖頁面showAll.html和showAuser.html 部分代碼如下
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>顯示查詢結(jié)果</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" rel="external nofollow" />
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" rel="external nofollow" />
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Spring Data JPA簡單查詢</h3>
</div>
</div>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><span th:text="${title}"></span></h3>
</div>
<div class="panel-body">
<div class="table table-responsive">
<tab
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
到此這篇關(guān)于Spring Boot深入學(xué)習(xí)數(shù)據(jù)訪問之Spring Data JPA與Hibernate的應(yīng)用的文章就介紹到這了,更多相關(guān)Spring Boot數(shù)據(jù)訪問內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot 簽到獎勵實現(xiàn)方案的示例代碼
這篇文章主要介紹了SpringBoot 簽到獎勵實現(xiàn)方案的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
Java實現(xiàn)將列表數(shù)據(jù)導(dǎo)出為PDF文件并添加水印
這篇文章主要為大家詳細(xì)介紹了如何使用Java實現(xiàn)把列表數(shù)據(jù)導(dǎo)出為PDF文件,同時加上PDF水印,文中的示例代碼講解詳細(xì),需要的可以參考下2024-02-02
java Beanutils.copyProperties( )用法詳解
這篇文章主要介紹了java Beanutils.copyProperties( )用法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
Java實現(xiàn)學(xué)生信息管理系統(tǒng)IO版本
這篇文章主要為大家詳細(xì)介紹了Java實現(xiàn)學(xué)生信息管理系統(tǒng)IO版本,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-04-04

