基于Spring Boot,使用JPA动态调用Sql查询数据
在《基于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查询数据的更多相关文章
- 基于Spring Boot,使用JPA调用Sql Server数据库的存储过程并返回记录集合
在上一篇<基于Spring Boot,使用JPA操作Sql Server数据库完成CRUD>中完成了使用JPA对实体数据的CRUD操作. 那么,有些情况,会把一些查询语句写在存储过程中,由 ...
- Spring Boot + Mybatis 实现动态数据源
动态数据源 在很多具体应用场景的时候,我们需要用到动态数据源的情况,比如多租户的场景,系统登录时需要根据用户信息切换到用户对应的数据库.又比如业务A要访问A数据库,业务B要访问B数据库等,都可以使用动 ...
- 基于Spring Boot和Spring Cloud实现微服务架构学习
转载自:http://blog.csdn.net/enweitech/article/details/52582918 看了几周Spring相关框架的书籍和官方demo,是时候开始总结下这中间的学习感 ...
- 基于Spring Boot和Spring Cloud实现微服务架构学习--转
原文地址:http://blog.csdn.net/enweitech/article/details/52582918 看了几周spring相关框架的书籍和官方demo,是时候开始总结下这中间的学习 ...
- 基于Spring Boot+Cloud构建微云架构
前言 首先,最想说的是,当你要学习一套最新的技术时,官网的英文文档是学习的最佳渠道.因为网上流传的多数资料是官网翻译而来,很多描述的重点也都偏向于作者自身碰到的问题,这样就很容易让你理解和操作出现偏差 ...
- 基于Spring Boot、Spring Cloud、Docker的微服务系统架构实践
由于最近公司业务需要,需要搭建基于Spring Cloud的微服务系统.遍访各大搜索引擎,发现国内资料少之又少,也难怪,国内Dubbo正统治着天下.但是,一个技术总有它的瓶颈,Dubbo也有它捉襟见肘 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合
文章目录 1. 环境依赖 2. 数据源 3. 脚本初始化 4. JPA 整合方案一 通过继承 JpaRepository 接口 4.1. 实体对象 4.2. DAO相关 4.3. Service相关 ...
- Spring Boot干货系列:(八)数据存储篇-SQL关系型数据库之JdbcTemplate的使用
Spring Boot干货系列:(八)数据存储篇-SQL关系型数据库之JdbcTemplate的使用 原创 2017-04-13 嘟嘟MD 嘟爷java超神学堂 前言 前面几章介绍了一些基础,但都是静 ...
- 基于Spring Boot和Spring Cloud实现微服务架构
官网的技术导读真的描述的很详细,虽然对于我们看英文很费劲,但如果英文不是很差,请选择沉下心去读,你一定能收获好多.我的学习是先从Spring boot开始的,然后接触到微服务架构,当然,这一切最大的启 ...
随机推荐
- [国嵌攻略][127][tty驱动程序架构]
tty概念解析 在Linux系统中,终端是一类字符型设备,它包括多种类型,通常使用tty来简称各种类型的终端设备. 1.串口终端(/dev/ttyS*) 串口终端是使用计算机串口连接的终端设备.Lin ...
- C#编写影院售票系统(A project with a higher amount of gold )
项目需求: 影院售票系统 1.基础设施 放映厅 座位集合 2.一个海报------------>放映计划 3.售票设置----------->观影 领域模型:程序中提炼出的实体 4.从电影 ...
- IOS学习笔记27—使用GDataXML解析XML文档
http://blog.csdn.net/ryantang03/article/details/7868246
- intern
java.lang.String的intern()方法"abc".intern()方法的返回值还是字符串"abc",表面上看起来好像这个方 法没什么用处.但实际 ...
- eclipse 按住ctrl 按钮没有反映
以下是修改为XML Editior打开方法Window -> Preferences -> General -> Editors -> File Associations Fi ...
- List源码学习之LinkedList
LinkedList 内部数据接口为一个链表,存储数据可为空可重复. 1.包含主要参数: //集合长度transient int size = 0; /** * 头结点 */ transient No ...
- 使用vue 遇到的问题————— 解决手机实时显示项目
Vue项目文件组织架构: src文件夹存放源代码. Static文件夹存放第三方静态资源. git将项目上传github http://blog.csdn.net/laozitianxia/ ...
- 使用SQL 提示优化sql
use index 在查询语句中表名的后面,添加use index来提供希望mysql去参考的索引列表,就可以让mysql不再考虑其他可用的索引 explain select * from renta ...
- jquery与js添加子元素
例如在select中添加option JQuery做法: <select id="myselect" name="myselect"> </s ...
- 使用SoapUI调用Vsphere Web Service
项目中经常需要调用Webservice进行验证测试,下面就介绍下如何使用测试工具SoapUI调用Vsphere vcenter的 Web Service VSphere的Webservice地址默认为 ...