基于Spring Boot,使用JPA动态调用Sql查询数据

2023-05-16

在《基于Spring Boot,使用JPA操作Sql Server数据库完成CRUD》,《基于Spring Boot,使用JPA调用Sql Server数据库的存储过程并返回记录集合》完成了CRUD,调用存储过程查询数据。

很多复杂的情况下,会存在要直接执行SQL来获取数据。

通过“EntityManager”创建NativeQuery方法来执行动态SQL。

 

1.查询结果集映射

在包“com.kxh.example.demo.domain”下的“Contact”实体上编写命名的结果集映射,因为可以写很多映射。

@SqlResultSetMapping注解即为映射。

name参数,可以为结果集映射取个名字。

entities参数,用来说明把Entity和查询的结果字段进行关联说明。


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
@SqlResultSetMapping(
        name = "conatctMapping", 
        entities = @EntityResult(
            entityClass = Contact.class, 
            fields = {
                @FieldResult(name = "name", column = "name"),
                @FieldResult(name = "phone", column = "phone"),
                @FieldResult(name = "mail", column = "mail")})
)
@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"创建NativeQuery函数,第一参数是Sql,第二个参数就是上面定义的结果集映射名。

然后传入查询条件参数,设置最大返回结果记录数,获取查询结果集。


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();
    }
    
    @SuppressWarnings("unchecked")
    public List<Contact> findAllByViaQuery(String name) {
        List<Contact> contacts = this.entityManager
                .createNativeQuery("select name, phone, mail from contact where name like :name", "conatctMapping")
                .setParameter("name", name)
                .setMaxResults(5)
                .getResultList();
        
        return contacts;
    }
}  

 

4.通过RestController向外提供服务

增加一个新的访问路径映射,在处理方法中调用contactsService.findAllByViaQuery(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;//省略
//通过动态sql查
    @RequestMapping(value="/query/viadnq/likename", method=RequestMethod.GET)
    public List<Contact> findContactsUseDyanamicQueryLikeName(String name) {
        System.out.println("kxh1");
        String nameWhere = org.apache.commons.lang.StringUtils.join(new String[]{"%", name, "%"}, "");
        List<Contact> contacts = contactsService.findAllByViaQuery(nameWhere);
        if(contacts == null) {
            System.out.println("kxh4");
            return new ArrayList<Contact>();
        } else {
            System.out.println("kxh5");
            return contacts;
        }
    }
}  

 

代码

 

End 

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

基于Spring Boot,使用JPA动态调用Sql查询数据 的相关文章

  • Windows 机器通过 FTP 上传文件

    用户可使用 FTP 通道 xff0c 将应用程序从本地服务器上传到云服务器中 操作步骤 步骤一 xff1a 在云服务器配置 FTP 服务 以 CentOS 系统为例 在 root 权限下 xff0c 通过命令 yum install vsf
  • Android:onNewIntent()触发机制及注意事项

    为什么80 的码农都做不了架构师 xff1f gt gt gt 一 onNewIntent 在 IntentActivity 中重写下列方法 xff1a onCreate onStart onRestart onResume onPause
  • 大气压随温度变化表_钓鱼与气压温度风向的关系春夏秋冬钓鱼最好时间图表

    详解钓鱼与气压之间的关系 xff1a 刀牛姐夫制作 欢迎留言 谢谢 什么样的气压适合钓鱼 xff1f 大气压力在1002 1054毫巴为好钓 xff1b 其中在1006 1028毫巴为很好钓 xff01 那么 xff0c 怎样才能了解气压的
  • linux的xstart命令怎么不能用,配置使通过Xmanager xstart远程连接linux

    安装gpm软件包 yum install gpm yum install gdm 1 编辑配置文件 etc gdm custom conf root 64 localhost vi etc gdm custom conf 找到以下两行 se
  • .NET Core 的缓存篇之MemoryCache

    前言 对于缓存我们都已经很熟悉了 缓存分为很多种 xff0c 浏览器缓存 试图缓存 服务器缓存 数据库缓存等等一些 xff0c 那今天我们先介绍一下视图缓存和MemoryCache内存缓存的概念和用法 xff1a 视图缓存 在老的版本的MV
  • 源码安装 MariaDB

    为什么80 的码农都做不了架构师 xff1f gt gt gt 官方文档 一 安装依赖组件 root 64 localhost yum y install gcc gcc c 43 43 make cmake ncurses ncurses
  • Centos的故障排除

    环境 xff1a centos 6 4 x86 64 所需工具 xff1a CentOS 6 4 x86 64 LiveDVD iso下载地址 xff1a http mirrors 163 com centos 6 4 isos 首先介绍
  • 服务器亮黄灯问题检查方法

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 找到硬盘和主板的位置 拔出主板 xff08 如图位置4块主板 xff09 xff0c 检查内存条是否松动 xff0c 建议重新插上内存 一个节点一块硬盘 xff0c 硬盘位
  • failed to open stream :HTTP request failed 解决方法

    用curl抓取 xff0c 不要用file get contents 前者比后者效率高一点 转载于 https www cnblogs com Basu p 7940167 html
  • Android通过第三方软件打开Word、Excel、PPT、PDF等文档

    近期公司有个需求 xff0c PDF格式需要在应用内打开浏览 xff0c Word Excel要求不高直接用第三方软件打开即可 xff0c 找了两种解决办法 第一 xff0c 全部在应用内打开 xff0c 可接入腾讯的TBS xff08 没
  • mariadb数据库文件的组成

    一 日志文件 1 错误日志 xff1a error log 错误日志记录msyql运行过程中所有较为严重的警告和错误信息 xff0c 以及mariadb server 每一次启动和关闭的详细信息 xff0c 事件调度运行一个事件时产生的信息
  • FTP中的授权规则

    在授权规则中 xff0c 你可以管理自己的FTP站点以怎样的方式进行访问 xff0c 比如每个进入站点的人都需要输入用户名密码 正则可以在授权规则中删除默认的配置 允许匿名用户读取 的规则 也可以在此处 xff0c 对不同的组或用户进行粒度
  • docker应用实例——httpd

    docker可以用来创建虚拟环境跑应用 xff0c 各个应用能起到隔离作用 步骤也很简单 xff0c 就是获取 下拉镜像 应用 xff0c 然后进行安装就可以了 1 搜索镜像 xff0c 比如我想虚拟一个httpd应用 xff0c 可以看到
  • curl: (1) Protocol "'http" not supported or disabled in libcurl

    Windows下安装Curl 下载的64位版本 下载后 xff0c 将以下文件复制到 D Windows 目录下 注意 xff1a 我的系统在D盘 但是使用以下命令时 xff1a curl X GET 39 http localhost 9
  • ios UILabel 字体设置 大全

    2019独角兽企业重金招聘Python工程师标准 gt gt gt code UILabel垂直居上对齐 label sizeToFit 设置文字过长时的显示格式 label lineBreakMode 61 UILineBreakMode
  • Activity关于onConfigurationChanged方法

    方法介绍 方法 xff1a public void onConfigurationChanged Configuration newConfig 场景 xff1a 当系统的 配置信息 发生改变时 xff0c 系统会调用此方法 前提是 xff
  • Ubuntu server10.4实现自动登录

    下面是网上找的方法 xff1a 注意 这里的修改要非常小心 xff0c 出来命令不能敲错之外 xff0c 一定要记得执行 chmod 43 x autologin xff0c 不然搞不好可能会导致启动不了 xff0c 我在操作的时候就因为忘
  • FTP服务器之身份验证、授权及隔离详解

    FTP 服务器之身份验证 授权及隔离 贰零壹叁年拾月国庆假期 YoloSntim 简介 Windows 中较为基本服务器功能 xff0c 提供文件上下载功能 可单服务器管理 xff0c 亦可与域集成在一起 网上有许多介绍及教程 xff0c
  • C++到底还能做什么?

    嗯 xff0c 这是一位朋友发到我邮箱里面的 xff0c 很奇怪 xff0c 发到了gmail邮箱 xff0c 而不是我常用的hotmail邮箱哈 我呢 xff0c 试着回答一下 xff0c 如果回答得不好 xff0c 叫做肖某人学艺不精
  • 年月日时的天干推算方法

    年干推算方法 公历年号计算农历年干支的方法与公式 查出公元4年为 甲子 年 故计算公式设公元后减3 xff1b 公元前减2 公元后农历年干支的计算方法 xff1a 天干计算 xff1a 公历年号的个位数 3即为天干序号 xff1b 个位为0

随机推荐