溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring boot與數(shù)據(jù)持久化Spring Data JPA集成實(shí)戰(zhàn)

發(fā)布時(shí)間:2020-07-07 15:18:20 來源:網(wǎng)絡(luò) 閱讀:1056 作者:墨營 欄目:軟件技術(shù)

數(shù)據(jù)持久化Spring Data JPA
項(xiàng)目集成了spring boot+spring data JPA+thymeleaf
前臺(tái)代碼地址:
https://blog.51cto.com/13501268/2319622
1.JPA理解:是用于管理Java EE和Java SE環(huán)境中的持久化,1.以及對(duì)象/關(guān)系映射的Java API

2.核心概念:

(1)實(shí)體:實(shí)體表示關(guān)系數(shù)據(jù)庫中的表

(2)每個(gè)實(shí)體實(shí)例對(duì)應(yīng)于該表中的行

(3)類必須用javas.persistence.Entity注解

(4)類必須有一個(gè)public或protected的的無參構(gòu)造函數(shù)

(5)實(shí)體實(shí)例被當(dāng)做值以分離對(duì)象方式進(jìn)行傳遞(例如通過會(huì)話bean的遠(yuǎn)程業(yè)務(wù)接口),則該類必須實(shí)現(xiàn)Serializable接口

(6)唯一的對(duì)象標(biāo)識(shí)符:簡(jiǎn)單主鍵(javax.persistence.Id),復(fù)合主鍵(javax.persistence.Embeddedld和javax.persistence.IdClass)

3.關(guān)系:

(1)一對(duì)一:@OneToOne

(2)一對(duì)多:@OneToMany

(3)多對(duì)一:@ManyToOne

(4)多對(duì)多:@ManyToMany

4.EntityManager接口:

(1)定義用于與持久化上下文進(jìn)行交互的方法

(2)創(chuàng)建和刪除持久化實(shí)例,通過實(shí)體的主鍵查找實(shí)體

5.Spring Data JPA:

(1)是更大的Spring Data家族的一部分

(2)對(duì)基于JPA的數(shù)據(jù)訪問層的增強(qiáng)支持

(3)更容易構(gòu)建基于使用Spring數(shù)據(jù)訪問技術(shù)棧的應(yīng)用

6.Spring Data JPA常用接口:

(1)CurdRepository:

Spring boot與數(shù)據(jù)持久化Spring Data JPA集成實(shí)戰(zhàn)

(2)PagingAndSortingRepository:

Spring boot與數(shù)據(jù)持久化Spring Data JPA集成實(shí)戰(zhàn)
7.Spring Data JPA自定義接口:

(1)根據(jù)方法名查詢,方法名命名一定要遵循規(guī)則

Spring boot與數(shù)據(jù)持久化Spring Data JPA集成實(shí)戰(zhàn)

8.Spring Data JPA,Hibernate與Spring Boot的集成

(1)環(huán)境配置:MySql數(shù)據(jù)庫,Hibernate框架,以及Mysql連接驅(qū)動(dòng)

(2)修改pom.xml文件,添加Spring Data JPA以及數(shù)據(jù)庫連接驅(qū)動(dòng)的依賴:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://×××w.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dhtt.spring.boot.blog</groupId>
    <artifactId>spring.data.action</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring.data.action</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 內(nèi)存數(shù)據(jù)庫h3 -->
        <!-- 
        <dependency>
            <groupId>com.h3database</groupId>
            <artifactId>h3</artifactId>
        </dependency>
         -->
        <!-- Mysql數(shù)據(jù)庫連接驅(qū)動(dòng) -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!-- hibernate持久層框架引入 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.3.7.Final</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

(3)啟動(dòng)項(xiàng)目進(jìn)行測(cè)試,我們發(fā)現(xiàn)項(xiàng)目正常啟動(dòng),說明我們的環(huán)境已經(jīng)配置好了

9.集成后臺(tái)編碼:

(1)User實(shí)體:加@Entity注解,唯一標(biāo)識(shí)@Id注解,制定主鍵生成策略,無參構(gòu)造改造為protected,防止直接使用,加toString方法,實(shí)現(xiàn)Serializable接口;

package com.dhtt.spring.boot.blog.spring.data.action.entity;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 * user實(shí)體
 * 
 * @author QT
 */
@Entity
public class User implements Serializable {

    private static final long serialVersionUID = 516988700978313579L;
    @Id // 主鍵
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增策略
    private Long id; // 用戶的唯一標(biāo)識(shí)
    private String name; // 用戶名
    private String email; // 用戶郵箱

    protected User() { // 防止直接使用
        super();
    }

    public User(Long id, String name, String email) {
        super();
        this.id = id;
        this.name = name;
        this.email = email;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", email=" + email + "]";
    }

}

(2)資源庫:寫userRepository接口繼承JpaRepository接口

package com.dhtt.spring.boot.blog.spring.data.action.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.dhtt.spring.boot.blog.spring.data.action.entity.User;
/**
 * User Repository接口
 * @author  QT
 *
 */
@Repository
public interface UserRepository extends JpaRepository<User, Long>{
}

(3)編寫userController類,用于與前臺(tái)進(jìn)行交互

package com.dhtt.spring.boot.blog.spring.data.action.web.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.dhtt.spring.boot.blog.spring.data.action.entity.User;
import com.dhtt.spring.boot.blog.spring.data.action.repository.UserRepository;

@Controller
@RequestMapping("/users")
public class userController {
    @Autowired
    private UserRepository userRepository;

    /**
     * 查詢所有用戶
     * 
     * @param model
     * @return
     */
    @GetMapping
    public ModelAndView getList(Model model) {
        model.addAttribute("userList", userRepository.findAll());
        model.addAttribute("title", "用戶管理");
        return new ModelAndView("users/list", "userModel", model);

    }

    /**
     * 根據(jù)Id查詢用戶
     * 
     * @param id
     * @param model
     * @return
     */
    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Long id, Model model) {
        User user = userRepository.getOne(id);
        model.addAttribute("user", user);
        model.addAttribute("title", "用戶查詢");
        return new ModelAndView("users/view", "userModel", model);

    }

    /**
     * 創(chuàng)建用戶
     * 
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/form")
    public ModelAndView createForm(Model model) {
        model.addAttribute("user", new User(null, null, null));
        model.addAttribute("title", "創(chuàng)建用戶");
        return new ModelAndView("users/form", "userModel", model);

    }

    /**
     * 新增或修改用戶
     * 
     * @param user
     * @return
     */
    @PostMapping
    public ModelAndView saveOrUpdateUser(User user) {
        user = userRepository.save(user);
        return new ModelAndView("redirect:/users", "userModel", user);

    }

    /**
     * 獲取刪除用戶
     * 
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public ModelAndView deleteUser(@PathVariable("id") Long id) {
        userRepository.deleteById(id);;
        return new ModelAndView("redirect:/users"); // 重定向到list頁面

    }

    /**
     * 獲取修改用戶界面
     * 
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/modify/{id}")
    public ModelAndView modify(@PathVariable("id") Long id, Model model) {
        User user = userRepository.getOne(id);
        model.addAttribute("user", user);
        model.addAttribute("title", "修改用戶");
        return new ModelAndView("users/form", "userModel", model);

    }
}

前臺(tái)與上一個(gè)項(xiàng)目一樣,直接粘貼復(fù)制就好

前臺(tái)代碼項(xiàng)目地址:

https://blog.51cto.com/13501268/2319622

接下里,啟動(dòng)項(xiàng)目,項(xiàng)目運(yùn)行正常說明集成成功,下一步我們就將數(shù)據(jù)進(jìn)行持久化到數(shù)據(jù)庫中

10.將數(shù)據(jù)持久化到數(shù)據(jù)庫中
(1)進(jìn)行數(shù)據(jù)庫配置,配置文件如下

#thymeleaf配置
spring.thymeleaf.encoding=UTF-8
#熱部署靜態(tài)文件,不需要緩存,實(shí)時(shí)觀察文件修改效果
spring.thymeleaf.cache=false
#使用html5標(biāo)準(zhǔn)
spring.thymeleaf.mode=HTML5
spring.thymeleaf.suffix=.html
spring.resources.chain.strategy.content.enabled=true

#數(shù)據(jù)庫連接配置
spring.datasource.url=jdbc:mysql://localhost:3306/blog_test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root
spring.datasource.password=qitao1996
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#jpa配置
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop

(2)接下來啟動(dòng)數(shù)據(jù)庫,建立數(shù)據(jù)庫
Spring boot與數(shù)據(jù)持久化Spring Data JPA集成實(shí)戰(zhàn)
接下來我們啟動(dòng)項(xiàng)目進(jìn)行操作,我們會(huì)發(fā)現(xiàn)數(shù)據(jù)庫表成功創(chuàng)建,也可以操作表中數(shù)據(jù)

至此,Spring boot+Spring Data Jpa+mevan+Thymeleaf集成成功完成

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI