Spring Data JPA 和 JPA

本文介绍了Spring Data JPA和JPA的概念,重点阐述了Spring Data的特点,如统一的Repository接口和JPA的集成。通过Spring Data JPA的例子,展示了如何定义Repository、Entity和配置,并探讨了一对多、多对一的关系以及JPQL的使用。
摘要由CSDN通过智能技术生成

Spring Data项目的目的是为了简化构建基于Spring框架应用的数据访问技术,包括非关系数据库、Map-Reduce框架、云数据服务等等;另外也包含堆关系数据库的访问支持。
Spring Data包含多个子项目:

  • Spring Data Commons
  • Spring Data JPA
  • Spring KeyValue
  • Spring Data LDAP
  • Spring Data MongoDB
  • Spring Data REST
  • Spring Data Redis
    …等

1. Spring Data特点

Spring Data为我们提供使用统一的API来对数据访问层进行操作;这主要是Spring Data Commons项目来实现的。Spring Data Commons让我们在使用关系型或非关系型数据访问技术时都基于Spring提供的统一标准,标准包含了CRUD、查询、排序和分页的相关操作。

2.统一的Repository接口

在这里插入图片描述

3. JPA与Spring Data

1)JpaRepository基本功能
编写接口继承JpaRepository既有CRUD及分页等基本功能
2)定义符合规范的名字命名
在接口中只需要声明符合规范的方法,即拥有对应的功能
以下是部分关键字

关键字 方法命名 sql where字句
And findByNameAndPwd where name= ? and pwd =?
Or findByNameOrSex where name= ? or sex=?
Is,Equals findById,findByIdEquals where id= ?
Between findByIdBetween where id between ? and ?
LessThan findByIdLessThan where id < ?
GreaterThan findByIdGreaterThan where id > ?
IsNull findByNameIsNull where name is null
isNotNull,NotNull findByNameNotNull where name is not null
Like findByNameLike where name like ?

3)@Query自定义查询,定制查询sql
4)Specfications查询

4. Spring Data、Spring Data JPA, JPA的关系

在这里插入图片描述

5. Spring Data JPA例子

Reposity:

//继承JpaRepository来完成对数据库的操作
public interface UserReposity extends JpaRepository<User,Integer> {
   

    List<User> getUserByIdGreaterThan(Integer id);
}

Entity:

//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据库映射的类)
@Table(name = "user") //来指定和那个数据表对应;如果省略默认表明就是user
public class User {
   

    @Id //表明这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) //自增主键
    private Integer id;

    @Column(name = "last_name", length = 50) //这是和数据表对应的一个列, 如果不设置name属性的值,默认为列名
    private String lastNme;

    private String email;
	...set/set...
}

配置:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/jpalearning?useUnicode=true&characterEncoding=UTF-8&serverTimezone=EST
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update #更新或者创建数据表结构
    show-sql: true #控制台显示sql

Controller:

@RestController
public class UserController {
   

    @Autowired
    UserReposity userReposity;

    @GetMapping("/user/{id}"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值