基於Spring Boot,使用JPA調用Sql Server數據庫的存儲過程並返回記錄集合


在上一篇《基於Spring Boot,使用JPA操作Sql Server數據庫完成CRUD》中完成了使用JPA對實體數據的CRUD操作。

那么,有些情況,會把一些查詢語句寫在存儲過程中,由存儲過程來返回記錄集。

在這里就先通過EntityManager創建命名存儲過程的方法完成調用。

 

1.創建SQL存儲過程

存儲過程返回所有的聯系人。

USE [demodb]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <bobenut>
-- Create date: <2017/9/14>
-- Description:    <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[proc_get_contacts_like_name]
    @name varchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    SELECT * from contact where name like @name;
END

 

2.定義命名的存儲過程。

在包“com.kxh.example.demo.domain”下的“Contact”實體上編寫存儲過程的映射。

@NamedStoredProcedureQueries注解表示可以包含多個存儲過程的映射。

@NamedStoredProcedureQuery注解就是對一個存儲過程的映射。

參數name,給這次映射取一個名字,后續調用時使用。

參數procedureName,是數據庫中真實的存儲過程的名字。

參數parameters,是對存儲過程輸入或輸出參數的映射定義。

package com.kxh.example.demo.domain;

import javax.persistence.Entity;
import javax.persistence.EntityResult;
import javax.persistence.FieldResult;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedStoredProcedureQueries;
import javax.persistence.NamedStoredProcedureQuery;
import javax.persistence.ParameterMode;
import javax.persistence.SqlResultSetMapping;
import javax.persistence.StoredProcedureParameter;

@Entity @NamedStoredProcedureQueries({ @NamedStoredProcedureQuery( name = "getContactsLikeName", procedureName = "proc_get_contacts_like_name", resultClasses = { Contact.class }, parameters = { @StoredProcedureParameter( mode = ParameterMode.IN, name = "name", type = String.class) } ) }) public class Contact {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    
    private String name;
    
    private String phone;
    
    private String mail;
    
    public Contact() {
        super();
    }
    
    public Contact(String name, String phone, String mail) {
        super();
        
        this.name = name;
        this.phone = phone;
        this.mail = mail;
    }
    
    public long getId() {
        return this.id;
    }
    
    public void setId(long value) {
        this.id = value;
    }
    
    public String getName() {
        return this.name;
    }
    
    public void setName(String value) {
        this.name = value;
    }
    
    public String getPhone() {
        return phone;
    }
    
    public void setPhone(String value) {
        this.phone = value;
    }
    
    public String getMail() {
        return this.mail;
    }
    
    public void setMail(String value) {
        this.mail = value;
    }
}

 

3.通過業務對象調用

在包“com.kxh.example.demo.service”下創建類“ContactsService”。

在類內,引入“EntityManager”,加上@Autowired注解由框架實例化。

通過"EntityManager"創建命名的存儲過程函數,並傳入上面定義的映射名進行指定調用。

然后為存儲過程設置輸入參數,執行並返回結果。

package com.kxh.example.demo.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.StoredProcedureQuery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.kxh.example.demo.domain.Contact;

@Component
public class ContactsService {
    @Autowired
    private EntityManager entityManager;
    
    @SuppressWarnings("unchecked")
    public List<Contact> findAllViaProc(String name) {
       StoredProcedureQuery storedProcedureQuery = this.entityManager.createNamedStoredProcedureQuery("getContactsLikeName");
       storedProcedureQuery.setParameter("name", name);
       storedProcedureQuery.execute();
       return storedProcedureQuery.getResultList();
    }
}

 

4.通過RestController向外提供服務

引入“ContactService”作為成員變量,並Autowired。

增加一個新的訪問路徑映射,在處理方法中調用contactsService.findAllViaProc(nameWhere)獲取查詢結果集。

package com.kxh.example.demo.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.kxh.example.demo.dao.ContactsRepository;
import com.kxh.example.demo.domain.Contact;
import com.kxh.example.demo.service.ContactsService;

@RestController
@RequestMapping("/contacts")
public class ContactsController {
        
    @Autowired
    ContactsService contactsService;
    //省略//通過存儲過程查
    @RequestMapping(value="/query/viaproc/likename", method=RequestMethod.GET)
    public List<Contact> findContactsUseProcLikeName(String name) {
        System.out.println("kxh1");
        String nameWhere = org.apache.commons.lang.StringUtils.join(new String[]{"%", name, "%"}, "");
        List<Contact> contacts = contactsService.findAllViaProc(nameWhere);
        if(contacts == null) {
            return new ArrayList<Contact>();
        } else {
            return contacts;
        }
    }
    
    //省略
}

 

代碼

 

End

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM