《基于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

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

  1. 基于Spring Boot,使用JPA调用Sql Server数据库的存储过程并返回记录集合

    在上一篇<基于Spring Boot,使用JPA操作Sql Server数据库完成CRUD>中完成了使用JPA对实体数据的CRUD操作. 那么,有些情况,会把一些查询语句写在存储过程中,由 ...

  2. Spring Boot + Mybatis 实现动态数据源

    动态数据源 在很多具体应用场景的时候,我们需要用到动态数据源的情况,比如多租户的场景,系统登录时需要根据用户信息切换到用户对应的数据库.又比如业务A要访问A数据库,业务B要访问B数据库等,都可以使用动 ...

  3. 基于Spring Boot和Spring Cloud实现微服务架构学习

    转载自:http://blog.csdn.net/enweitech/article/details/52582918 看了几周Spring相关框架的书籍和官方demo,是时候开始总结下这中间的学习感 ...

  4. 基于Spring Boot和Spring Cloud实现微服务架构学习--转

    原文地址:http://blog.csdn.net/enweitech/article/details/52582918 看了几周spring相关框架的书籍和官方demo,是时候开始总结下这中间的学习 ...

  5. 基于Spring Boot+Cloud构建微云架构

    前言 首先,最想说的是,当你要学习一套最新的技术时,官网的英文文档是学习的最佳渠道.因为网上流传的多数资料是官网翻译而来,很多描述的重点也都偏向于作者自身碰到的问题,这样就很容易让你理解和操作出现偏差 ...

  6. 基于Spring Boot、Spring Cloud、Docker的微服务系统架构实践

    由于最近公司业务需要,需要搭建基于Spring Cloud的微服务系统.遍访各大搜索引擎,发现国内资料少之又少,也难怪,国内Dubbo正统治着天下.但是,一个技术总有它的瓶颈,Dubbo也有它捉襟见肘 ...

  7. Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合

    文章目录 1. 环境依赖 2. 数据源 3. 脚本初始化 4. JPA 整合方案一 通过继承 JpaRepository 接口 4.1. 实体对象 4.2. DAO相关 4.3. Service相关 ...

  8. Spring Boot干货系列:(八)数据存储篇-SQL关系型数据库之JdbcTemplate的使用

    Spring Boot干货系列:(八)数据存储篇-SQL关系型数据库之JdbcTemplate的使用 原创 2017-04-13 嘟嘟MD 嘟爷java超神学堂 前言 前面几章介绍了一些基础,但都是静 ...

  9. 基于Spring Boot和Spring Cloud实现微服务架构

    官网的技术导读真的描述的很详细,虽然对于我们看英文很费劲,但如果英文不是很差,请选择沉下心去读,你一定能收获好多.我的学习是先从Spring boot开始的,然后接触到微服务架构,当然,这一切最大的启 ...

随机推荐

  1. [国嵌笔记][030][U-Boot工作流程分析]

    uboot工作流程分析 程序入口 1.打开顶层目录的Makefile,找到目标smdk2440_config的命令中的第三项(smdk2440) 2.进入目录board/samsung/smdk244 ...

  2. 从零开始学习前端开发 — 9、标签嵌套规则及CSS常用样式覆盖

    1. 块级元素可以包含内联元素或某些块级元素,但内联元素却不能包含块级元素,它只能包含其它的内联元素: <div><h1></h1><p></p& ...

  3. [field:softlinks/]逻辑过程

    在plus/download.php 在dededln\include\taglib\channel\softlinks.lib.php

  4. ThinkPhp5.0_文件上传

    ===================================================================== 路径: F:\wamp\www\public\uploads ...

  5. MySQL Block Nested Loop and Batched Key Access Joins(块嵌套循环和批量Key访问连接)

    Block Nested-Loop and Batched Key Access Joins Batched Key Access (BKA) Join算法通过index和join buffer访问j ...

  6. servlet入门学习之工作原理解析

    从 Servlet 容器说起 要介绍 Servlet 必须要先把 Servlet 容器说清楚,Servlet 与 Servlet 容器的关系有点像枪和子弹的关系,枪是为子弹而生,而子弹又让枪有了杀伤力 ...

  7. JavaScript Date 时间对象方法

    Date(日期/时间对象) Date 操作日期和时间的对象 Date.getDate( ) 返回一个月中的某一天 Date.getDay( ) 返回一周中的某一天 Date.getFullYear( ...

  8. AMS常见问题

      1.安装完AMS是否就可以实现直播点播了? 答:是的,ams运行后,就可以提供各种协议的直播输出地址,和点播地址:不过一般情况下客户还得需要另外的Web系统来配合使用,来完成对前台用户界面的友好化 ...

  9. Servlet--ServletInputStream类,ServletOutputStream类

    ServletInputStream类 定义 public abstract class ServletInputStream extends InputStream 这个类定义了一个用来读取客户端的 ...

  10. 基于jsmpeg库下使用ffmpeg创建视频流连接websocket中继器传输视频并播放

    这个功能的基本工作是这样的: 1.使用node运行jsmpeg库下的websocket-relay.js文件,这个文件的作用是创建一个websocket视频传输中继器 2.运行ffmpeg,将输出发送 ...