在 SPRING Boot JPA 中调用带有本机查询中的参数的存储过程
创始人
2024-01-28 10:46:09
0

配置pom.xml


4.0.0org.springframework.bootspring-boot-starter-parent2.2.0.M1 com.demoSpringBootDataJPA0.0.1-SNAPSHOTSpringBootDataJPASpring Boot Data JPA1.8org.springframework.bootspring-boot-starter-data-jpamysqlmysql-connector-javaruntimenet.bytebuddybyte-buddy1.9.12org.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-maven-pluginspring-snapshotsSpring Snapshotshttps://repo.spring.io/snapshottruespring-milestonesSpring Milestoneshttps://repo.spring.io/milestonespring-snapshotsSpring Snapshotshttps://repo.spring.io/snapshottruespring-milestonesSpring Milestoneshttps://repo.spring.io/milestone


 

创建数据库

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

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

创建商店过程

DELIMITER $$
CREATE PROCEDURE sp_findBetween(min decimal, max decimal)
BEGINSELECT * FROM product where price BETWEEN min and max;
END $$
DELIMITER ;

产品表的结构

产品表数据


 

数据库配置

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

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

实体类

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

package com.demo.entities;import java.io.Serializable;import java.math.BigDecimal;import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;@Entity
@Table(name = "product")
public class Product implements Serializable {private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private int id;private String name;private BigDecimal price;private int quantity;private String description;private String photo;private boolean featured;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public BigDecimal getPrice() {return price;}public void setPrice(BigDecimal price) {this.price = price;}public int getQuantity() {return quantity;}public void setQuantity(int quantity) {this.quantity = quantity;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getPhoto() {return photo;}public void setPhoto(String photo) {this.photo = photo;}public boolean isFeatured() {return featured;}public void setFeatured(boolean featured) {this.featured = featured;}}


 

产品存储库接口

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

package com.demo.repositories;import java.math.BigDecimal;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.demo.entities.Product;@Repository("productRepository")
public interface ProductRepository extends CrudRepository {@Query(value = "{call sp_findBetween(:min, :max)}", nativeQuery = true)public List findAllBetweenStoredProcedure(@Param("min") BigDecimal min, @Param("max") BigDecimal max);}

产品服务接口

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

package com.demo.services;import java.math.BigDecimal;
import java.util.List;
import com.demo.entities.Product;public interface ProductService {public List findAllBetweenStoredProcedure(BigDecimal min, BigDecimal max);}

产品服务类

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

package com.demo.services;import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.demo.entities.Product;
import com.demo.repositories.ProductRepository;@Transactional
@Service("productService")
public class ProductServiceImpl implements ProductService {@Autowiredprivate ProductRepository productRepository;@Overridepublic List findAllBetweenStoredProcedure(BigDecimal min, BigDecimal max) {return productRepository.findAllBetweenStoredProcedure(min, max);}}


 

JPA 配置

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

package com.demo;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;import com.demo.services.ProductService;
import com.demo.services.ProductServiceImpl;@Configuration
@EnableAutoConfiguration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "com.demo.repositories" })
@ComponentScan("com.demo")
@PropertySource("classpath:application.properties")
public class JPAConfiguration {@Beanpublic ProductService productService() {return new ProductServiceImpl();}}

项目结构


 

应用

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

package com.demo.main;import java.math.BigDecimal;import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;import com.demo.JPAConfiguration;
import com.demo.entities.Product;
import com.demo.services.ProductService;public class Demo {public static void main(String[] args) {try {AbstractApplicationContext context = new AnnotationConfigApplicationContext(JPAConfiguration.class);ProductService productService = context.getBean(ProductService.class);System.out.println("Find product have price between 4 and 8");for (Product product : productService.findAllBetweenStoredProcedure(BigDecimal.valueOf(4), BigDecimal.valueOf(8))) {System.out.println("Id: " + product.getId());System.out.println("Name: " + product.getName());System.out.println("Price: " + product.getPrice());System.out.println("========================");}context.close();} catch (Exception e) {System.out.println(e.getMessage());}}}

输出

Id: 4
Name: Computer 1
Price: 5.0
========================
Id: 5
Name: Computer 2
Price: 7.0
========================
Id: 12
Name: Laptop 2
Price: 4.0
========================

相关内容

热门资讯

成都世运会进入倒计时30天 7月8日,成都世运会进入倒计时30天。赛会将于8月7日至8月17日在成都举行。图为成都天府广场倒计时...
小本创业平民项目 小本创业平民... 小本创业:500元起家到月入20万_创业小项目发布日期:2017-03-17来源:创业小项目作者:小...
2011年小本创业流水增涨项目... 现在什么小本生意流水增涨5个“特色小吃”项目推荐!2017年08月03日来源:渠道网现在什么小本生意...
流水增涨的小本创业2011年小... 解答一、美容美发店  美容美发业女人的“美丽产业”大有流水增涨机会。女性买菜时可能会为了一两块钱而计...
关于互联网创业 ”大学生创新创... 人家是如何做呢?先就是分析需求,目前各行各业都有培训,教各种技能的。找一个自己比较刚需的领域,我拿微...
适合白领创业的六大小本创业项万... 阅读本文前,请您先点击上面的蓝色字体“创业之坛”,再点击“关注”,这样您就可以继续免费收到最新文章了...
城镇小本创业项目有哪些?小本项... 现在创业不同于之前,投资也会少很多,不少人在外打工了几年,想要回到自己的小城镇做点小本创业的买卖,那...
现在小本创业有什么好项目 现在... 为什么穷人多不敢去创业蛋糕创业蛋糕店创业30岁现在小本创业有什么好项目女人创业做什么适合女性创业的大...
五万元小本创业好项目 五万元小... 为什么穷人多不敢去创业蛋糕创业蛋糕店创业30岁女人创业做什么适合女性创业的大学生适合什么创业毕业生如...
5万元小本生意做什么好 做点什... 如今市场上有着很多的投资小项目,而导致这些项目出现的原因自然是因为当下人们生活水平以及消费水平的迅速...