使用Spring Data REST将Spring Data JPA存储库导出为REST服务

Spring Data模块提供了各种模块,以统一的方式处理各种类型的数据源,如RDBMS,NOSQL存储等。 在我以前的文章SpringMVC4 + Spring Data JPA +使用JavaConfig的SpringSecurity配置中,我已经解释了如何使用JavaConfig配置Spring Data JPA。

现在,在这篇文章中,让我们看看如何使用Spring Data JPA存储库以及如何使用Spring Data REST将JPA实体导出为REST端点。

首先,让我们在pom.xml中配置spring-data-jpa和spring-data-rest-webmvc依赖项。

<dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-jpa</artifactId><version>1.5.0.RELEASE</version>
</dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-rest-webmvc</artifactId><version>2.0.0.RELEASE</version>
</dependency>

确保正确配置了最新发布的版本,否则将遇到以下错误:

java.lang.ClassNotFoundException: org.springframework.data.mapping.SimplePropertyHandler

创建JPA实体。

@Entity
@Table(name = "USERS")
public class User implements Serializable
{private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "user_id")private Integer id;@Column(name = "username", nullable = false, unique = true, length = 50)private String userName;@Column(name = "password", nullable = false, length = 50)private String password;@Column(name = "firstname", nullable = false, length = 50)private String firstName;@Column(name = "lastname", length = 50)private String lastName;@Column(name = "email", nullable = false, unique = true, length = 50)private String email;@Temporal(TemporalType.DATE)private Date dob;private boolean enabled=true;@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)@JoinColumn(name="user_id")private Set<Role> roles = new HashSet<>();@OneToMany(mappedBy = "user")private List<Contact> contacts = new ArrayList<>();//setters and getters}@Entity
@Table(name = "ROLES")
public class Role implements Serializable
{private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "role_id")private Integer id;@Column(name="role_name",nullable=false)private String roleName;//setters and getters}@Entity
@Table(name = "CONTACTS")
public class Contact implements Serializable
{private static final long serialVersionUID = 1L;@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name = "contact_id")private Integer id;@Column(name = "firstname", nullable = false, length = 50)private String firstName;@Column(name = "lastname", length = 50)private String lastName;@Column(name = "email", nullable = false, unique = true, length = 50)private String email;@Temporal(TemporalType.DATE)private Date dob;@ManyToOne@JoinColumn(name = "user_id")private User user;//setters and getters}

使用AbstractAnnotationConfigDispatcherServletInitializer配置DispatcherServlet。 观察到我们已经将RepositoryRestMvcConfiguration.class添加到getServletConfigClasses()方法中。 RepositoryRestMvcConfiguration是一个繁重的工作,它寻找Spring Data Repository并将其导出为REST端点。

package com.sivalabs.springdatarest.web.config;import javax.servlet.Filter;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;import com.sivalabs.springdatarest.config.AppConfig;public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{@Overrideprotected Class<?>[] getRootConfigClasses(){return new Class<?>[] { AppConfig.class};}@Overrideprotected Class<?>[] getServletConfigClasses(){return new Class<?>[] { WebMvcConfig.class, RepositoryRestMvcConfiguration.class };}@Overrideprotected String[] getServletMappings(){		return new String[] { "/rest/*" };}	@Overrideprotected Filter[] getServletFilters() {return new Filter[]{new OpenEntityManagerInViewFilter()};} 
}

为JPA实体创建Spring Data JPA存储库。

public interface UserRepository extends JpaRepository<User, Integer>
{
}public interface RoleRepository extends JpaRepository<Role, Integer>
{
}public interface ContactRepository extends JpaRepository<Contact, Integer>
{
}

而已。 Spring Data REST将负责其余的工作。

您可以使用spring Rest Shell https://github.com/spring-projects/rest-shell或Chrome的Postman插件来测试导出的REST服务。

D:\rest-shell-1.2.1.RELEASE\bin>rest-shell
http://localhost:8080:>

现在我们可以使用baseUri命令更改baseUri,如下所示:

http://localhost:8080:>baseUri http://localhost:8080/spring-data-rest-demo/rest/http://localhost:8080/spring-data-rest-demo/rest/>http://localhost:8080/spring-data-rest-demo/rest/>listrel         href======================================================================================users       http://localhost:8080/spring-data-rest-demo/rest/users{?page,size,sort}roles       http://localhost:8080/spring-data-rest-demo/rest/roles{?page,size,sort}contacts    http://localhost:8080/spring-data-rest-demo/rest/contacts{?page,size,sort}

注意:当DispatcherServlet url映射到“ /”时,rest-shell似乎存在问题,并且它发出的list list命令以“未找到资源”作为响应。

http:// localhost:8080 / spring-data-rest-demo / rest />获取用户/

{"_links": {"self": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/{?page,size,sort}","templated": true},"search": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/search"}},"_embedded": {"users": [{"userName": "admin","password": "admin","firstName": "Administrator","lastName": null,"email": "admin@gmail.com","dob": null,"enabled": true,"_links": {"self": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/1"},"roles": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/1/roles"},"contacts": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/1/contacts"}}},{"userName": "siva","password": "siva","firstName": "Siva","lastName": null,"email": "sivaprasadreddy.k@gmail.com","dob": null,"enabled": true,"_links": {"self": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/2"},"roles": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/2/roles"},"contacts": {"href": "http://localhost:8080/spring-data-rest-demo/rest/users/2/contacts"}}}]},"page": {"size": 20,"totalElements": 2,"totalPages": 1,"number": 0}
}
  • 您可以在https://github.com/sivaprasadreddy/sivalabs-blog-samples-code/tree/master/spring-data-rest-demo中找到源代码
  • 有关Spring Rest Shell的更多信息: https : //github.com/spring-projects/rest-shell

参考: “ 我的实验”博客上的 JCG合作伙伴 Siva Reddy 使用Spring Data REST将Spring Data JPA存储库导出为REST服务 。

翻译自: https://www.javacodegeeks.com/2014/03/exporting-spring-data-jpa-repositories-as-rest-services-using-spring-data-rest.html

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

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

相关文章

如何在ftp服务器下查找文件夹,查找ftp服务器下的文件夹名

查找ftp服务器下的文件夹名 内容精选换一换Linux x86-64(64位)服务器&#xff0c;常见的有EulerOS、Ubuntu、Debian、CentOS、OpenSUSE等。Windows 7及以上版本。请参见JRE地址下载JRE。Linux服务器安装请参考如下步骤&#xff1a;使用root用户&#xff0c;进入/opt目录。cd /o…

Spring入门篇——第6章 Spring AOP的API介绍

第6章 Spring AOP的API介绍 主要介绍Spring AOP中常用的API。6-1 Spring AOP API的Pointcut、advice概念及应用 映射方法是sa开头的所有方法 如果当前是被锁住&#xff0c;并且方法的名称中包含set&#xff0c;那也就是说我们不希望执行set方法去改变物体本身的属性&#xff0…

微信机器人开发SDK使用教程--养号任务停止

微信机器人开发SDK使用教程--养号任务停止 case "PostStopWeChatMaintenanceTask": {// 养号任务停止 log.debug("websocket:msgtypePostStopWeChatMaintenanceTask。。。。。"); postStopWeChatMaintenanceTaskWebsocketHandler.handleMsg(ctx, vo, conte…

图的长宽_华为P50 Pro渲染图曝光:单挖孔屏+超高屏占比

去年下半年&#xff0c;华为发布 Mate 40 旗舰系列&#xff0c;由于麒麟芯片的供应限制以及受到消费者的热捧&#xff0c;Mate 40 系列部分型号至今仍一机难求&#xff1b;此前&#xff0c;有数条爆料曝光了华为新旗舰 P50 系列手机的相关信息&#xff0c;该系列有望在今年上半…

你从未见过的 HTML5 动画效果

HTML5 的 Canvas 对象将改变 JavaScript 的使命&#xff0c;使之成为 HTML5 下强大的动画脚本编写工具。本文介绍了 8 个你从未见过的&#xff0c;基于 HTML5 Canvas 和 JavaScript 的动画&#xff0c;这些令人难以置信的效果将使你对 HTML5 彻底折服。需要指出的是&#xff0c…

使用Java EE的ManagedExecutorService异步执行事务

自Java EE 7规范发布以来已经过去了一年。 现在&#xff0c;Wildfly 8 Final已发布&#xff0c;现在是时候仔细看看这些新功能了。 自从Java EE时代开始以来就缺少的一件事是能够使用成熟的Java EE线程。 Java EE 6已经为我们带来了Asynchronous批注&#xff0c;通过它我们可以…

离线存储网页服务器无响应,网页保存应注意的问题

您可能感兴趣的话题&#xff1a;IE核心提示&#xff1a;从IE5.0开始&#xff0c;我们浏览网页的时候&#xff0c;能够选择“另存网页”&#xff0c;然后断线脱机浏览&#xff0c;大大节省了在线的网络费用。从IE5.0开始&#xff0c;我们浏览网页的时候&#xff0c;能够选择“另…

在Ubuntu主机下实现与Windows虚拟机共享文件夹

一&#xff0e;概述 由于要实现&#xff35;buntu主机中的一些文件与Windows虚拟机共享&#xff0c;因此要创建一个共享文件夹映射到虚拟机中&#xff0e; 网上许多都是&#xff37;indows主机&#xff0b;&#xff2c;inux虚拟机的配置&#xff0c;在此分享主机是&#xff2c;…

Appium环境搭建-完整版

环境依赖 Node.jsAppiumAppium-desktopAppium-doctorAppium-Python-ClientPythonJDKAndriod SDK以上所需的软件本套教程素材包都提供&#xff0c;可以在视频左下角【获取素材】去对应章节下载&#xff0c;找到Appium环境配置全家桶。 安装Node.js 下载地址&#xff1a;https://…

ubuntu更新python的指令_ubuntu下python模块的库更新(转载)

ubuntu下python模块的库更新亲测有用&#xff0c;非常好ubuntu中python模块的库下载一般用pip安装。然而有时候pip的下载源在国外&#xff0c;就导致下载速度非常慢。这里提供一个方法&#xff1a;首先命令行进入&#xff1a; cd ~/.pip在这个文件夹下面找到(如果没有则自己创建…

配置安全域名https申请免费证书并配置nginx运行环境

补全信息时选项 在这一步需要去查看进度&#xff0c;下载对应文件上传到对应站点根目录里按照要求建的隐藏类型的文件 如下图 讲证书文件按照下面操作 进行配置项配置https 如下 详情下载附件 server { listen 443; server_name wap.ssgsrz.com; ssl on; root /web/wap_ssgsr…

为什么要在Java SE 7的数字中使用下划线-在数字文字中使用下划线

JDK 1.7发行版引入了几个有用的功能&#xff0c;尽管其中大多数都是语法糖&#xff0c;但使用该功能可以大大提高可读性和代码质量。 这样的功能之一是在数字文字中引入下划线 。 从Java 7开始&#xff0c;您可以在Java源代码中向可读性更高的10_000_000_000写一个长数字&#…

如何刻录服务器安装系统光盘启动盘,如何刻录系统光盘

如何刻录系统光盘大家更多的是使用第三方刻录软件&#xff0c;但是win7系统自带刻录功能可以刻录系统盘。那么如何刻录系统光盘&#xff0c;怎么刻录系统盘?下面小编就来给大家介绍如何刻录系统光盘方法。win7系统自带刻录功能刻录系统光盘方法&#xff1a;一、前期准备&#…

plsql导入csv数据,未响应,invalid identifier

问题分析&#xff1a; 1.确保cvs字段名与表字段名一致&#xff0c;不要有空格 2.cvs字段对应表字段的大写&#xff0c;确保表字段都是大写 3.如果字段能对应上&#xff0c;plsql会自动识别出来转载于:https://www.cnblogs.com/code4app/p/9935365.html

微信小程序之发送模板消息(通过openid推送消息给用户)

一、获取access_token access_token是接口调用的凭证&#xff0c;目前有效期为两个小时&#xff0c;需要定时刷新&#xff0c;重复获取将导致上次获取的access_token失效。&#xff08;注&#xff1a;不建议每次调用需要access_token的接口&#xff0c;都去重新获取access_toke…

python全栈开发内容_Python全栈开发之Day02

一. 回顾上节主要内容1. python是一门解释型弱类型高级语言2. python的解释器CPython, PyPy, JPython, IronPython, Ipython3. print(内容1, 内容2)4. 变量程序运行过程中产生的中间值, 暂时存储在内存中.供后面的程序使用命名规范:1. 由字母, 数字, 下户线组成2. 不能是数字开…

JBoss模块很糟糕,无法在JBoss 7下使用自定义Resteasy / JAX-RS

由于JBoss EAP 6.1 / AS 7.2.0是模块化的&#xff0c;并且您可以排除Web应用程序可见的模块&#xff0c;因此您希望可以轻松地忽略内置的JAX-RS实现&#xff08;Rest Easy 2.3.6&#xff09;并使用它。自定义的&#xff08;3.0.6&#xff09;。 但是&#xff0c;可悲的是&#…

Ansible-----条件判断与错误处理

when 在ansible中&#xff0c;条件判断的关键词是when --- - hosts: allremote_user: roottasks:- debug:msg: "System release is centos"when: ansible_distribution "CentOS"ansible_distribution就是facts信息中的一个key&#xff0c;之前如果我们需要…

Ansible 运维自动化 ( 配置管理工具 )

一、关于AnsibleAnsible是一个自动化部署工具;Ansible通过SSH协议实现远程节点和管理节点之间的通信。理论上说&#xff0c;只要管理员通过ssh登录到一台远程主机上能做的操作&#xff0c;Ansible都可以做到。Ansible是python开发的,故依赖一些python库和组件,如:paramiko&…

分解 python_面试官:如何用Python实现将一个整数分解成质因数?

概述今天主要分享一个关于分解质因数的实例&#xff0c;判断的逻辑稍微多了点&#xff0c;一起来看看吧~需求将一个整数分解质因数。例如&#xff1a;输入90,打印出90233*5思路其实根本不需要判断是否是质数&#xff0c;从2开始向数本身遍历&#xff0c;能整除的肯定是最小的质…