将自定义功能添加到Spring数据存储库

Spring Data非常方便,并且避免了样板代码,从而加快了开发速度。 但是,在某些情况下,注释查询不足以实现您可能想要实现的自定义功能。

因此,spring数据允许我们向Spring数据存储库添加自定义方法。 我将使用前一篇博客文章中的相同项目结构。

我们有一个名为Employee的实体

package com.gkatzioura.springdata.jpa.persistence.entity;import javax.persistence.*;/*** Created by gkatzioura on 6/2/16.*/
@Entity
@Table(name = "employee", schema="spring_data_jpa_example")
public class Employee {@Id@Column(name = "id")@GeneratedValue(strategy = GenerationType.SEQUENCE)private Long id;@Column(name = "firstname")private String firstName;@Column(name = "lastname")private String lastname;@Column(name = "email")private String email;@Column(name = "age")private Integer age;@Column(name = "salary")private Integer salary;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getFirstName() {return firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}public String getLastname() {return lastname;}public void setLastname(String lastname) {this.lastname = lastname;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Integer getSalary() {return salary;}public void setSalary(Integer salary) {this.salary = salary;}
}

还有Spring Data存储库

package com.gkatzioura.springdata.jpa.persistence.repository;import com.gkatzioura.springdata.jpa.persistence.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;/*** Created by gkatzioura on 6/2/16.*/
@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long>{}

假设我们要添加一些自定义的sql功能,例如使用LIKE语句查询并与未映射为实体的表联接。

这仅用于演示目的。 对于您的项目,您可能会有更好的架构。 再加上spring数据具有类似语句的开箱即用功能,请查看EndingWith,Containing,StartingWith 。

我们将创建奖金表并添加对雇员表的引用。

set schema 'spring_data_jpa_example';create table bonus(id serial primary key,employee_id integer,amount real,foreign key (employee_id) references employee (id),unique (employee_id));insert into bonus
( employee_id, amount)
VALUES(1, 100);

我们要实现的sql查询将查询名称以指定文本开头且奖金大于一定数量的员工。 在jdbc中,我们必须传递与字符'%'串联在一起的变量。

所以我们需要一个像这样的本地jpa查询

Query query = entityManager.createNativeQuery("select e.* from spring_data_jpa_example.bonus b, spring_data_jpa_example.employee e\n" +"where e.id = b.employee_id " +"and e.firstname LIKE ? " +"and b.amount> ? ", Employee.class);query.setParameter(1, firstName + "%");query.setParameter(2, bonusAmount);

为了将此功能添加到我们的spring数据存储库中,我们必须添加一个接口。 我们的界面必须遵循$ {Original Repository name} Custom的命名约定。 因此,描述我们自定义功能的界面应为

package com.gkatzioura.springdata.jpa.persistence.repository;import com.gkatzioura.springdata.jpa.persistence.entity.Employee;import java.util.List;/*** Created by gkatzioura on 6/3/16.*/
public interface EmployeeRepositoryCustom {List<Employee> getFirstNamesLikeAndBonusBigger(String firstName, Double bonusAmount);}

实施应该是

package com.gkatzioura.springdata.jpa.persistence.repository;import com.gkatzioura.springdata.jpa.persistence.entity.Employee;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;/*** Created by gkatzioura on 6/3/16.*/
@Repository
@Transactional(readOnly = true)
public class EmployeeRepositoryImpl implements EmployeeRepositoryCustom {@PersistenceContextEntityManager entityManager;@Overridepublic List<Employee> getFirstNamesLikeAndBonusBigger(String firstName, Double bonusAmount) {Query query = entityManager.createNativeQuery("select e.* from spring_data_jpa_example.bonus b, spring_data_jpa_example.employee e\n" +"where e.id = b.employee_id " +"and e.firstname LIKE ? " +"and b.amount> ? ", Employee.class);query.setParameter(1, firstName + "%");query.setParameter(2, bonusAmount);return query.getResultList();}
}

并且我们应该更改原始的spring数据存储库以继承自定义功能。

package com.gkatzioura.springdata.jpa.persistence.repository;import com.gkatzioura.springdata.jpa.persistence.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;/*** Created by gkatzioura on 6/2/16.*/
@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long>, EmployeeRepositoryCustom {
}

似乎是一种不错的构图方式。 现在让我们向控制器添加一个方法,该方法将调用此自定义方法

package com.gkatzioura.springdata.jpa.controller;import com.gkatzioura.springdata.jpa.persistence.entity.Employee;import com.gkatzioura.springdata.jpa.persistence.repository.EmployeeRepository;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import java.util.List;/*** Created by gkatzioura on 6/2/16.*/
@RestController
public class TestController {@Autowiredprivate EmployeeRepository employeeRepository;@RequestMapping("/employee")public List<Employee> getTest() {return employeeRepository.findAll();}@RequestMapping("/employee/filter")public List<Employee> getFiltered(String firstName,@RequestParam(defaultValue = "0") Double bonusAmount) {return employeeRepository.getFirstNamesLikeAndBonusBigger(firstName,bonusAmount);}}

源代码可以在github上找到。

翻译自: https://www.javacodegeeks.com/2016/06/add-custom-functionality-spring-data-repository.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/352938.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mysql concat的使用

想要在一个id前都加个0,如果处理呢? mysql concat的使用 update a_data set idCONCAT(0, id) where data_packet_id in (2774, 2775, 2776);转载于:https://www.cnblogs.com/djwhome/p/9554086.html

biweb wms门户网站php开源建站系统 v5.8.3,BIWEB WMS PHP开源企业建站系统 v5.8.5

BIWEB WMS 企业版升级啦&#xff01;&#xff01;&#xff01;现推出中英文双语版&#xff0c;并可以完美支持中文繁简转换。该系统需要PHP5以上版本&#xff0c;并要开启PDO和PDO_MYSQL组件&#xff0c;否则无法使用。BIWEB V5.8.5启用了新的底层框架&#xff0c;共享内存缓存…

Edmonds_Karp 算法 (转)

找了好久终于在这个牛这里找到为什么反向边要加回流量的原因了&#xff0c; 因为是初学教程&#xff0c;所以我会尽量避免繁杂的数学公式和证明。也尽量给出了较为完整的代码。 本文的目标群体是网络流的初学者&#xff0c;尤其是看了各种NB的教程也没看懂怎么求最大流的小盆友…

Grid表格的js触发事件

没怎么接触过Grid插件&#xff1b; 解决的问题是&#xff1a;点击Grid表行里的内容触发js方法弹出模态框&#xff0c;用以显示选中内容的详细信息。 思路&#xff1a;给准备要触发的列加上一个css属性&#xff0c;通过这个css属性来获取元素并触发js方法。 1 function flowGrid…

php 合并数组成父子关系,php - 将电子表格解析为PHP数组并返回具有父子关系的嵌套MLM表 - SO中文参考 - www.soinside.com...

这里有一些非递归代码可以让你开始(如果你还没有解决它)&#xff0c;它将根据从电子表格加载的$rows数组构建一个树。这个想法是每个节点都有一个名称和一个子数组。所以代码只是在步骤1中为每个人(父和子)创建一个节点&#xff0c;然后从下到上填写步骤2中的链接。代码不健壮&…

在JVM上对高并发HTTP服务器进行基准测试

在第一篇有关HTTP客户端的文章 &#xff08;我将您重定向到JVM上的高效HTTP的介绍&#xff09;之后&#xff0c;现在让我们讨论HTTP 服务器 。 有一些关于HTTP服务器的基准测试&#xff0c;但是它们经常受到诸如以下缺点的阻碍&#xff1a; 没有有效地执行高并发方案&#xf…

时间常用api

1.常用api 创建 Date 对象 - 年 - 月 - 日 - 小时 - 分 - 秒 - 星期 var nownew Date() var year now.getFullYear(); var month now.getMonth(); &#xff08;月 &#xff1a;0 - 11 &#xff0c;处理&#xff1a; month month 1;&#xff09; var da…

最大流的算法——Edmonds-Karp算法(最短路径增广算法)

最大流的算法——Edmonds-Karp算法(最短路径增广算法) 这里介绍一个最简单的算法:Edmonds-Karp算法 即最短路径增广算法 简称EK算法 EK算法基于一个基本的方法:Ford-Fulkerson方法 即增广路方法 简称FF方法 增广路方法是很多网络流算法的基础 一般都在残留网络中实现 其思路是每…

php做一个计算日期之间天数,PHP计算任意两个日期之间的天数

PHP面试题中&#xff0c;关于日期的题目作为基础考题经常出现&#xff0c;下面讨论一下获取两个日期之间的天数的方法。收到一个答案&#xff0c;拆分年、月、日&#xff0c;分别进行减法&#xff0c;然后统计天数&#xff0c;好累。针对低版本的PHP可以用下面的方式搞定&#…

[usaco2004][bzoj3379] 交作业

按距离从小到大排序 f[i][j][0或1]表示在i或j还有i-j没有完成 转移 tmpdp[i][j][0];tmpmin(tmp,max(dp[i][j1][1]a[j1].dist-a[i].dist,a[i].t));tmpmin(tmp,max(dp[i-1][j][0]a[i].dist-a[i-1].dist,a[i].t)); 注意边界 比如&#xff1a;dp[0][i],dp[0][c3]初值应为inf #inclu…

程序员的快速成长之路

在一封与TechRepublic会员交流的邮件当中&#xff0c;他提到了面向程序员的博客、文章及杂志分成两类&#xff1a;面向初学者类&#xff08;"hello world"这种类型的教程&#xff09;以及面向专家类&#xff08;MSDN杂志&#xff09;。这个观点很好&#xff0c;有关程…

oracle 强制 断开,ORA-01092: ORACLE 例程终止 强行断开连接

今天测试部门的人叫我过去&#xff0c;说是数据库当了&#xff0c;起不来了。我过去看了看情况&#xff0c;做了如下操作SQL> shutdown immediate数据库已经关闭。已经卸载数据库。Oracle 例程已经关闭。SQL> startupORACLE 例程已经启动。Total System Global Area 135…

weblogic运行项目_在WebLogic 12c上运行RichFaces

weblogic运行项目我最初以为我可以在几个月前写这篇文章。 但是我最终被不一样的事情所淹没。 其中之一是&#xff0c;它无法像我在4.0版本中那样简单地启动RichFaces展示柜。 有了所有的JMS magic和不同的提供程序检查&#xff0c;这已经成为简单构建和部署它的挑战。 无论如何…

超详细在Ubuntu下安装JDK图文解析

我们选择的是jdk1.6.0_30版本。安装文件名为jdk-6u30-linux-i586.bin. 1、复制jdk到安装目录 &#xff08;1&#xff09;假设jdk安装文件在桌面&#xff0c;我们指定的安装目录是&#xff1a;/usr/local/java 。可是系统安装后在/usr/local下并没有java目录&#xff0c;这需要…

oracle 整个表空间迁移,oracle11g迁移表空间

表空间名为sbjc&#xff0c;要从D:\APP\ORACLE\ORADATA\TABLESPACE\SBJC.DBF 迁移到 F:\oracle\oradata\tablespace\SBJC.DBF。 扼要操作步骤&#xff1a; 第一步&#xff1a;登陆数据库 第二步&#xff1a;中止数据库 第三步&#xff1a;在open方式下启动数据库 第四步&#x…

Qt5使用QFtp,二次封装

1、需要的东西 ftp.cpp,ftp.h是二次封装的ftp类&#xff0c;放在工程下包含 QFtp和qftp.h放在D:\Qt5.7.1\5.7\msvc2013\include\QtNetwork&#xff1b; Qt5Ftp.lib和Qt5Ftpd.lib是编译生成的库&#xff0c;放在工程源文件下 2、包含库 #pragma comment(lib,"Qt5Ftpd.lib&q…

无参数泛型方法反模式

最近&#xff0c;有关Java泛型的一个非常有趣的问题发布到Stack Overflow和reddit上。 考虑以下方法&#xff1a; <X extends CharSequence> X getCharSequence() {return (X) "hello"; }尽管不安全的转换看起来有些古怪&#xff0c;并且您可能会猜这里有些问…

oracle数据库升级失败,Oracle 11.2.0.1 rac 升级失败后,数据库降级方案(flashback database)...

升级失败后&#xff0c;数据库降级方案(flashback database)环境&#xff1a;Oracle 11.2.0.1 rac on redhat 5.8Flashback database准备工作查看是否flashback database功能sysRACDB>select log_mode,open_mode,flashback_on fromv$database;LOG_MODEOPEN_MODE …

Ubuntu下安装Oracle11g(图文教程)

由于课程需要&#xff0c;要在Ubuntu下安装一个Oracle&#xff0c;之前都没有装过&#xff0c;所以想通过这篇博文记录一下 1.下载Oracle 11g 下载地址&#xff1a;http://www.oracle.com/technetwork/database/enterprise-edition/downloads/index-092322.html 我选择下载的是…

class12_pack_grid_place 放置位置

其中的部分运行效果图&#xff08;程序见序号1&#xff09;&#xff1a; #!/usr/bin/env python# -*- coding:utf-8 -*-# ------------------------------------------------------------## 参考资料&#xff1a;# 用 python 和 tkinter 做简单的窗口视窗 - 网易云课堂# https:…