• 在 SPRING Boot JPA 中调用带有本机查询中的参数的存储过程


    配置pom.xml

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0modelVersion>
    6. <parent>
    7. <groupId>org.springframework.bootgroupId>
    8. <artifactId>spring-boot-starter-parentartifactId>
    9. <version>2.2.0.M1version>
    10. <relativePath />
    11. parent>
    12. <groupId>com.demogroupId>
    13. <artifactId>SpringBootDataJPAartifactId>
    14. <version>0.0.1-SNAPSHOTversion>
    15. <name>SpringBootDataJPAname>
    16. <description>Spring Boot Data JPAdescription>
    17. <properties>
    18. <java.version>1.8java.version>
    19. properties>
    20. <dependencies>
    21. <dependency>
    22. <groupId>org.springframework.bootgroupId>
    23. <artifactId>spring-boot-starter-data-jpaartifactId>
    24. dependency>
    25. <dependency>
    26. <groupId>mysqlgroupId>
    27. <artifactId>mysql-connector-javaartifactId>
    28. <scope>runtimescope>
    29. dependency>
    30. <dependency>
    31. <groupId>net.bytebuddygroupId>
    32. <artifactId>byte-buddyartifactId>
    33. <version>1.9.12version>
    34. dependency>
    35. <dependency>
    36. <groupId>org.springframework.bootgroupId>
    37. <artifactId>spring-boot-starter-testartifactId>
    38. <scope>testscope>
    39. dependency>
    40. dependencies>
    41. <build>
    42. <plugins>
    43. <plugin>
    44. <groupId>org.springframework.bootgroupId>
    45. <artifactId>spring-boot-maven-pluginartifactId>
    46. plugin>
    47. plugins>
    48. build>
    49. <repositories>
    50. <repository>
    51. <id>spring-snapshotsid>
    52. <name>Spring Snapshotsname>
    53. <url>https://repo.spring.io/snapshoturl>
    54. <snapshots>
    55. <enabled>trueenabled>
    56. snapshots>
    57. repository>
    58. <repository>
    59. <id>spring-milestonesid>
    60. <name>Spring Milestonesname>
    61. <url>https://repo.spring.io/milestoneurl>
    62. repository>
    63. repositories>
    64. <pluginRepositories>
    65. <pluginRepository>
    66. <id>spring-snapshotsid>
    67. <name>Spring Snapshotsname>
    68. <url>https://repo.spring.io/snapshoturl>
    69. <snapshots>
    70. <enabled>trueenabled>
    71. snapshots>
    72. pluginRepository>
    73. <pluginRepository>
    74. <id>spring-milestonesid>
    75. <name>Spring Milestonesname>
    76. <url>https://repo.spring.io/milestoneurl>
    77. pluginRepository>
    78. pluginRepositories>
    79. project>


     

    创建数据库

    创建一个名为springbootdatajpa 的数据库。此数据库有一个表:产品

    1. --
    2. -- Table structure for table `product`
    3. --
    4. CREATE TABLE `product` (
    5. `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    6. `name` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
    7. `price` decimal(10,1) NOT NULL,
    8. `quantity` int(11) NOT NULL,
    9. `description` text COLLATE utf8_unicode_ci NOT NULL,
    10. `photo` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
    11. `featured` tinyint(1) NOT NULL
    12. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    13. --
    14. -- Dumping data for table `product`
    15. --
    16. INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Mobile 1', '2.0', 2, 'description 1', 'thumb1.gif', 0);
    17. INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Mobile 2', '1.0', 5, 'description 2', 'thumb2.gif', 1);
    18. INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Mobile 3', '3.0', 9, 'description 3', 'thumb3.gif', 0);
    19. INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Computer 1', '5.0', 12, 'description 4', 'thumb1.gif', 1);
    20. INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Computer 2', '7.0', 5, 'description 5', 'thumb1.gif', 0);
    21. INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Computer 3', '12.0', 2, 'description 6', 'thumb2.gif', 1);
    22. INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Laptop 1', '3.0', 8, 'description 7', 'thumb2.gif', 0);
    23. INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Laptop 2', '4.0', 11, 'description 8', 'thumb3.gif', 1);
    24. INSERT INTO `product` (`name`, `price`, `quantity`, `description`, `photo`, `featured`) VALUES('Laptop 3', '2.0', 15, 'description 9', 'thumb2.gif', 0);

    创建存储过程

    1. DELIMITER $$
    2. CREATE PROCEDURE sp_findBetween(min decimal, max decimal)
    3. BEGIN
    4. SELECT * FROM product where price BETWEEN min and max;
    5. END $$
    6. DELIMITER ;

    产品表的结构

    产品表数据


     

    数据库配置

    src/main/resources文件夹中打开application.properties文件,并添加连接到数据库的配置,如下所示:

    1. spring.datasource.url= jdbc:mysql://localhost:3306/springbootdatajpa
    2. spring.datasource.username=root
    3. spring.datasource.password=123456

    实体类

    创建名为com.demo.entities 的新包。在此包中,创建名为 Product 的新 java 类.java如下所示:

    1. package com.demo.entities;
    2. import java.io.Serializable;
    3. import java.math.BigDecimal;
    4. import javax.persistence.Column;
    5. import javax.persistence.Entity;
    6. import javax.persistence.GeneratedValue;
    7. import javax.persistence.GenerationType;
    8. import javax.persistence.Id;
    9. import javax.persistence.Table;
    10. @Entity
    11. @Table(name = "product")
    12. public class Product implements Serializable {
    13. private static final long serialVersionUID = 1L;
    14. @Id
    15. @GeneratedValue(strategy = GenerationType.IDENTITY)
    16. private int id;
    17. private String name;
    18. private BigDecimal price;
    19. private int quantity;
    20. private String description;
    21. private String photo;
    22. private boolean featured;
    23. public int getId() {
    24. return id;
    25. }
    26. public void setId(int id) {
    27. this.id = id;
    28. }
    29. public String getName() {
    30. return name;
    31. }
    32. public void setName(String name) {
    33. this.name = name;
    34. }
    35. public BigDecimal getPrice() {
    36. return price;
    37. }
    38. public void setPrice(BigDecimal price) {
    39. this.price = price;
    40. }
    41. public int getQuantity() {
    42. return quantity;
    43. }
    44. public void setQuantity(int quantity) {
    45. this.quantity = quantity;
    46. }
    47. public String getDescription() {
    48. return description;
    49. }
    50. public void setDescription(String description) {
    51. this.description = description;
    52. }
    53. public String getPhoto() {
    54. return photo;
    55. }
    56. public void setPhoto(String photo) {
    57. this.photo = photo;
    58. }
    59. public boolean isFeatured() {
    60. return featured;
    61. }
    62. public void setFeatured(boolean featured) {
    63. this.featured = featured;
    64. }
    65. }


     

    产品存储库接口

    创建名为com.demo.repository 的新包。在这个包中,创建名为ProductRepository的新接口.java从 Spring Framework 的CrudRepository接口实现如下:

    1. package com.demo.repositories;
    2. import java.math.BigDecimal;
    3. import java.util.List;
    4. import org.springframework.data.jpa.repository.Query;
    5. import org.springframework.data.repository.CrudRepository;
    6. import org.springframework.data.repository.query.Param;
    7. import org.springframework.stereotype.Repository;
    8. import com.demo.entities.Product;
    9. @Repository("productRepository")
    10. public interface ProductRepository extends CrudRepository {
    11. @Query(value = "{call sp_findBetween(:min, :max)}", nativeQuery = true)
    12. public List findAllBetweenStoredProcedure(@Param("min") BigDecimal min, @Param("max") BigDecimal max);
    13. }

    产品服务接口

    创建名为com.demo.services 的新包。在此包中创建名为ProductService的新接口.java如下所示:

    1. package com.demo.services;
    2. import java.math.BigDecimal;
    3. import java.util.List;
    4. import com.demo.entities.Product;
    5. public interface ProductService {
    6. public List findAllBetweenStoredProcedure(BigDecimal min, BigDecimal max);
    7. }

    产品服务类

    com.demo.services包中,创建名为ProductServiceImpl的新java类.java从ProductService接口实现

    1. package com.demo.services;
    2. import java.math.BigDecimal;
    3. import java.util.List;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.stereotype.Service;
    6. import org.springframework.transaction.annotation.Transactional;
    7. import com.demo.entities.Product;
    8. import com.demo.repositories.ProductRepository;
    9. @Transactional
    10. @Service("productService")
    11. public class ProductServiceImpl implements ProductService {
    12. @Autowired
    13. private ProductRepository productRepository;
    14. @Override
    15. public List findAllBetweenStoredProcedure(BigDecimal min, BigDecimal max) {
    16. return productRepository.findAllBetweenStoredProcedure(min, max);
    17. }
    18. }


     

    JPA 配置

    com.demo包中,创建名为JPAConfiguration的新 java 类.java如下所示:

    1. package com.demo;
    2. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    3. import org.springframework.context.annotation.Bean;
    4. import org.springframework.context.annotation.ComponentScan;
    5. import org.springframework.context.annotation.Configuration;
    6. import org.springframework.context.annotation.PropertySource;
    7. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
    8. import org.springframework.transaction.annotation.EnableTransactionManagement;
    9. import com.demo.services.ProductService;
    10. import com.demo.services.ProductServiceImpl;
    11. @Configuration
    12. @EnableAutoConfiguration
    13. @EnableTransactionManagement
    14. @EnableJpaRepositories(basePackages = { "com.demo.repositories" })
    15. @ComponentScan("com.demo")
    16. @PropertySource("classpath:application.properties")
    17. public class JPAConfiguration {
    18. @Bean
    19. public ProductService productService() {
    20. return new ProductServiceImpl();
    21. }
    22. }

    项目结构


     

    应用

    创建名为com.demo.main 的新包。在此包中,创建名为 demo 的新 java 文件.java如下所示:

    1. package com.demo.main;
    2. import java.math.BigDecimal;
    3. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    4. import org.springframework.context.support.AbstractApplicationContext;
    5. import com.demo.JPAConfiguration;
    6. import com.demo.entities.Product;
    7. import com.demo.services.ProductService;
    8. public class Demo {
    9. public static void main(String[] args) {
    10. try {
    11. AbstractApplicationContext context = new AnnotationConfigApplicationContext(JPAConfiguration.class);
    12. ProductService productService = context.getBean(ProductService.class);
    13. System.out.println("Find product have price between 4 and 8");
    14. for (Product product : productService.findAllBetweenStoredProcedure(BigDecimal.valueOf(4), BigDecimal.valueOf(8))) {
    15. System.out.println("Id: " + product.getId());
    16. System.out.println("Name: " + product.getName());
    17. System.out.println("Price: " + product.getPrice());
    18. System.out.println("========================");
    19. }
    20. context.close();
    21. } catch (Exception e) {
    22. System.out.println(e.getMessage());
    23. }
    24. }
    25. }

    输出

    1. Id: 4
    2. Name: Computer 1
    3. Price: 5.0
    4. ========================
    5. Id: 5
    6. Name: Computer 2
    7. Price: 7.0
    8. ========================
    9. Id: 12
    10. Name: Laptop 2
    11. Price: 4.0
    12. ========================
  • 相关阅读:
    MySQL数据库学习【进阶篇】
    ARM64平台jetson nano上安装PyQt5环境
    C语言-找鞍点
    Creator 2.4.x 分享游戏图片
    【接口干货】热门、免费api集合
    uniapp scroll-view 下拉刷新动画无法关闭问题
    智能语音外呼系统 OKCC没有电脑的坐席能不能开展工作
    Elasticsearch实现检索词自动补全(检索词补全,自动纠错,拼音补全,繁简转换) 包含demo
    时序预测 | MATLAB实现基于SVM-Adaboost支持向量机结合AdaBoost时间序列预测
    EdgeMoE: Fast On-Device Inference of MoE-based Large Language Models
  • 原文地址:https://blog.csdn.net/allway2/article/details/127908062