SpringBoot 中JPA集成PostgreSql(详细说明)

SpringBoot 中JPA集成PostgreSql(详细说明)

什么是JPA(Java Persistence API)

Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA based repositories. This module deals with enhanced support for JPA based data access layers. It makes it easier to build Spring-powered applications that use data access technologies.

Implementing a data access layer of an application has been cumbersome for quite a while. Too much boilerplate code has to be written to execute simple queries as well as perform pagination, and auditing. Spring Data JPA aims to significantly improve the implementation of data access layers by reducing the effort to the amount that’s actually needed. As a developer you write your repository interfaces, including custom finder methods, and Spring will provide the implementation automatically.

Features

  • Sophisticated support to build repositories based on Spring and JPA
  • Support for Querydsl predicates and thus type-safe JPA queries
  • Transparent auditing of domain class
  • Pagination support, dynamic query execution, ability to integrate custom data access code
  • Validation of @Query annotated queries at bootstrap time
  • Support for XML based entity mapping
  • JavaConfig based repository configuration by introducing @EnableJpaRepositories.

国内说法

JPA 是指 Java Persistence API,即 Java 的持久化规范,一开始是作为 JSR-220 的一部分。
JPA 的提出,主要是为了简化 Java EE 和 Java SE 应用开发工作,统一当时的一些不同的 ORM 技术。
一般来说,规范只是定义了一套运作的规则,也就是接口,而像我们所熟知的Hibernate 则是 JPA 的一个实现(Provider)。

JPA 定义了什么,大致有:

  • ORM 映射元数据,用来将对象与表、字段关联起来
  • 操作API,即完成增删改查的一套接口
  • JPQL 查询语言,实现一套可移植的面向对象查询表达式

PostgreSQL简介

PostGreSQL是一个功能强大的开源对象关系数据库管理系统(ORDBMS),号称世界上最先进的开源关系型数据库
经过长达15年以上的积极开发和不断改进,PostGreSQL已在可靠性、稳定性、数据一致性等获得了很大的提升。
对比时下最流行的 MySQL 来说,PostGreSQL 拥有更灵活,更高度兼容标准的一些特性。
此外,PostGreSQL基于MIT开源协议,其开放性极高,这也是其成为各个云计算大T 主要的RDS数据库的根本原因。

JPA中使用PostgreSQL

一、添加依赖包

Spring Boot Mavn项目 Pom.xml文件中添加依赖包

<!--jpa与postgresql-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <!--<scope>runtime</scope>-->
</dependency>

二、配置PostgreSQL和jpa

application.properties文件中添加如下:

#数据库基本信息配置
spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/yourdatabase
spring.datasource.username=yourusername
spring.datasource.password=yourpassword
spring.jpa.show-sql=true
#JPA相关配置
spring.jpa.database=postgresql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false

注意:

  • yourdatabase,yourusername,yourpassword等信息是否配置正确。

  • spring.jpa.hibernate.ddl-auto 指定为 update,这样框架会自动帮我们创建或更新表结构

三、定义Entity

package com.book.entity;

import lombok.Data;

import javax.persistence.*;

@Data
@Entity
@Table(name = "bookshelf")
public class BookshelfItem {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column(name = "bookName",nullable = false)
    private String bookName;
    @Column(name = "describe")
    private String describe;
    @Column(name = "detail")
    private String detail;

    public  String  ToString()
    {
        return bookName + "-" + describe;
    }

}

注意:

  • 如果你的数据库中有自己创建的嵌套schema,要在Table属性中进行写明@Table(name = “bookshelf”,schema = “yourschema”)
  • bookName这样的写法会导致如果数据库没有这个数据元,则会创建成book_name

四、定义repository

package com.book.repository;

import com.book.entity.BookshelfItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface BookshelfRepository extends JpaRepository<BookshelfItem,Integer> {
    @Query(value = "select * from bookshelf",nativeQuery = true)
    List<BookshelfItem> GetAllBookData();
    @Query(value = "select * from bookshelf where book_name = :bookName",nativeQuery = true)
    List<BookshelfItem> GetBooksByName(@Param("bookName") String bookName);
}

注意:

  • 如果**@Query中有*号**,要在尾部加上nativeQuery = true

五、定义service

package com.book.service;

import com.book.entity.BookshelfItem;
import com.book.repository.BookshelfRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookshelfService {
    @Autowired
    private BookshelfRepository bookshelfRepository;
    public List<BookshelfItem> GetAll()
    {
        return  bookshelfRepository.GetAllBookData();
    }
    public List<BookshelfItem> GetNyBookname(String bookName)
    {
        return  bookshelfRepository.GetBooksByName(bookName);
    }

}

单元测试

package com.book;

import com.book.entity.BookshelfItem;
import com.book.service.BookshelfService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class BookApplicationTests {
    @Autowired
    BookshelfService bookshelfService;
    @Test
    public void contextLoads() {

        System.out.println("Get book All");
        List<BookshelfItem> temp = bookshelfService.GetAll();
        for (int i = 0; i < temp.size(); i++) {
            BookshelfItem item = temp.get(i);
            System.out.println(item.toString());
        }
        System.out.println("Get book by Name");
        temp = bookshelfService.GetNyBookname("boo1");
        for (int i = 0; i < temp.size(); i++) {
            BookshelfItem item = temp.get(i);
            System.out.println(item.toString());
        }
    }

}

本人测试结果如下(数据为我自己在数据库中添加的两条数据):

2019-10-08 17:01:07.646  INFO 4276 --- [           main] com.book.BookApplicationTests            : Started BookApplicationTests in 4.878 seconds (JVM running for 5.5)
Get book All
Hibernate: select * from bookshelf
BookshelfItem(id=1, bookName=boo1, describe=sdfsad, detail=sdfgdg)
BookshelfItem(id=2, bookName=boo2, describe=jkjkjk, detail=aaaaaa)
Get book by Name
Hibernate: select * from bookshelf where book_name = ?
BookshelfItem(id=1, bookName=boo1, describe=sdfsad, detail=sdfgdg)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.406 s - in com.book.BookApplicationTests
  • 10
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
"springboot基于vue的工厂车间管理系统的设计.zip" 是一个压缩包文件,通常包含了一套用于管理工厂车间运营的软件系统的源代码和相关资源。这个系统采用流行的前后端分离架构,后端使用Spring Boot框架,前端则采用Vue.js框架进行开发。以下是对这个资源的简要介绍:后端(Spring Boot): Spring Boot是一个开源的Java基础项目,用来简化Spring应用的初始搭建以及开发过程。它提供了大量的起步依赖,可以快速地构建出企业级的应用程序。在工厂车间管理系统,Spring Boot负责处理业务逻辑、数据库交互、安全性、服务接口(API)的提供等后端功能。前端(Vue.js): Vue.js是一个轻量级的JavaScript框架,用于构建用户界面。它易于上手,高效,且可灵活应用于单页面应用或多页面应用的开发。在此系统,Vue.js用于创建动态的用户界面,提供实时数据展示、交互操作和前后端的通信。系统功能: 这套工厂车间管理系统可能包括了生产计划管理、设备监控、员工排班、库存管理、质量控制、报表统计等模块,以帮助提高生产效率、减少浪费、确保产品质量,并提供数据分析支持决策。数据库: 系统可能使用MySQL、PostgreSQL或其他关系型数据库来存储数据,通过JPA (Java Persistence API) 或者MyBatis等ORM (Object-Relational Mapping) 工具与Spring Boot集成,实现数据的持久化。间件: 为了提高系统性能和扩展性,可能还会集成消息队列(如RabbitMQ)、缓存(如Redis)等间件。安全: 系统安全性由Spring Security提供,包括用户认证和权限控制等功能。跨平台: 由于使用了Web技术,该系统理论上可以在任何支持现代浏览器的设备上运行,包括PC、平板和手机等。开发文档: 通常情况下,源码包会包含README文件和相关文档,指导开发者如何运行和定制这套系统。技术支持: 如果源码是从一个开源社区获得的,那么开发者可能会从社区得到一些技术支持和功能更新。综上所述,"springboot基于vue的工厂车间管理系统的设计.zip" 提供了一个全栈的解决方案,适用于需要构建一个工厂车间管理系统的企业或个人开发者。它结合了当前流行的技术栈,旨在为用户提供一个可靠、高效、易于维护和扩展的系统。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值