Spring Data JPA简介
Spring Data JPA是较大的Spring Data系列的一部分,它基于JPA,增强了数据访问功能,使用Spring Data JPA可以很方便的访问数据库,不需要写很多代码模板。
Spring Data大家族
Spring Data的主要功能是为数据访问提供一个简单规范的基于Spring的编程模型。
它使使用数据访问技术,支持关系型数据库比如mysql和非关系数据库比如redis。
下面是Spring Data的家族成员:
- Spring Data Commons - Core Spring concepts underpinning every Spring Data module.
- Spring Data JDBC - Spring Data repository support for JDBC.
- Spring Data JDBC Ext - Support for database specific extensions to standard JDBC including support for Oracle RAC fast connection failover, AQ JMS support and support for using advanced data types.
- Spring Data JPA - Spring Data repository support for JPA.
- Spring Data KeyValue - Map based repositories and SPIs to easily build a Spring Data module for key-value stores.
- Spring Data LDAP - Spring Data repository support for Spring LDAP.
- Spring Data MongoDB - Spring based, object-document support and repositories for MongoDB.
- Spring Data Redis - Easy configuration and access to Redis from Spring applications.
- Spring Data REST - Exports Spring Data repositories as hypermedia-driven RESTful resources.
- Spring Data for Apache Cassandra - Easy configuration and access to Apache Cassandra or large scale, highly available, data oriented Spring applications.
- Spring Data for Apache Geode - Easy configuration and access to Apache Geode for highly consistent, low latency, data oriented Spring applications.
- Spring Data for Apache Solr - Easy configuration and access to Apache Solr for your search oriented Spring applications.
- Spring Data for Pivotal GemFire - Easy configuration and access to Pivotal GemFire for your highly consistent, low latency/high through-put, data oriented Spring applications.
JPA是一个规范,并非具体的实现框架,而Spring Data JPA就是依赖于Hibernate JPA的实现
下面通过一个例子来简单介绍下Spring Data JPA
Spring Data Jpa例子
1.新建一个工程
这里我分别勾选了Spring Web,Spring Data Jpa,Mysql Driver
建完工程需要加一下数据库连接池,这里我用的是的
alibaba的druid。
2.新建个数据库
create table user
(
user_id bigint not null comment '用户id',
name varchar(64) null comment '姓名',
age int null comment '年龄',
sex smallint null comment '性别',
mobile varchar(64) null comment '手机号',
mail varchar(64) null comment '邮箱'
)
comment '用户表';
3.开始写代码
为user表新建bean类,代码如下:
新建UserRepository实现JpaRepository接口,代码如下:
再来个Controller,代码如下:
下面就可以启动项目了。
4.最后测试一下接口
postman测试一下
看一下数据库是否成功
真香!