当前位置: 首页 > news >正文

Spring Boot 系列教程2-Data JPA

Spring Data JPA

用来简化创建 JPA 数据访问层和跨存储的持久层功能。

官网文档连接

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/

Spring Data JPA提供的接口

  • Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组件扫描的时候自动识别
  • CrudRepository :是Repository的子接口,提供CRUD的功能
  • PagingAndSortingRepository:是CrudRepository的子接口,添加分页和排序的功能
  • JpaRepository:是PagingAndSortingRepository的子接口,增加了一些实用的功能,比如:批量操作等
  • JpaSpecificationExecutor:用来做负责查询的接口
  • Specification:是Spring Data JPA提供的一个查询规范,要做复杂的查询,只需围绕这个规范来设置查询条件即可
    这里写图片描述

项目图片

这里写图片描述

pom.xml

-只需要在pom.xml引入需要的数据库配置,就会自动访问此数据库,如果需要配置其他数据库,可以在application.properties进行添加
-默认使用org.apache.tomcat.jdbc.pool.DataSource创建连接池

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jege.spring.boot</groupId>
    <artifactId>spring-boot-data-jpa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-data-jpa</name>
    <url>http://maven.apache.org</url>

    <!-- 公共spring-boot配置,下面依赖jar文件不用在写版本号 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!-- 持久层 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- h2内存数据库 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <finalName>spring-boot-data-jpa</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

User.java

package com.jege.spring.boot.data.jpa.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:jpa模型对象
 */
@Entity
@Table(name = "t_user")
public class User {
  @Id
  @GeneratedValue
  private Long id;
  private String name;
  private Integer age;

  public User() {

  }

  public User(String name, Integer age) {
    this.name = name;
    this.age = age;
  }

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Integer getAge() {
    return age;
  }

  public void setAge(Integer age) {
    this.age = age;
  }

}

UserRepository.java

package com.jege.spring.boot.data.jpa.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.jege.spring.boot.data.jpa.entity.User;

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:持久层接口,由spring自动生成其实现
 */
public interface UserRepository extends JpaRepository<User, Long> {

  List<User> findByNameLike(String name);

}

Repository接口查询规则

关键字案例效果
AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname… where x.lastname = ?1 or x.firstname = ?2
Is,EqualsfindByFirstname,findByFirstnameIs,findByFirstnameEquals… where x.firstname = ?1
BetweenfindByStartDateBetween… where x.startDate between ?1 and ?2
LessThanfindByAgeLessThan… where x.age < ?1
LessThanEqualfindByAgeLessThanEqual… where x.age <= ?1
GreaterThanfindByAgeGreaterThan… where x.age > ?1
GreaterThanEqualfindByAgeGreaterThanEqual… where x.age >= ?1
AfterfindByStartDateAfter… where x.startDate > ?1
BeforefindByStartDateBefore… where x.startDate < ?1
IsNullfindByAgeIsNull… where x.age is null
IsNotNull,NotNullfindByAge(Is)NotNull… where x.age not null
LikefindByFirstnameLike… where x.firstname like ?1
NotLikefindByFirstnameNotLike… where x.firstname not like ?1
StartingWithfindByFirstnameStartingWith… where x.firstname like ?1 (parameter bound with appended %)
EndingWithfindByFirstnameEndingWith… where x.firstname like ?1 (parameter bound with prepended %)
ContainingfindByFirstnameContaining… where x.firstname like ?1 (parameter bound wrapped in %)
OrderByfindByAgeOrderByLastnameDesc… where x.age = ?1 order by x.lastname desc
NotfindByLastnameNot… where x.lastname <> ?1
InfindByAgeIn(Collection ages)… where x.age in ?1
NotInfindByAgeNotIn(Collection age)… where x.age not in ?1
TRUEfindByActiveTrue()… where x.active = true
FALSEfindByActiveFalse()… where x.active = false
IgnoreCasefindByFirstnameIgnoreCase… where UPPER(x.firstame) = UPPER(?1)

Application.java

package com.jege.spring.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:spring boot 启动类
 */

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

}

application.properties

## JPA Settings
spring.jpa.generate-ddl: true
spring.jpa.show-sql: true
spring.jpa.hibernate.ddl-auto: create
spring.jpa.properties.hibernate.format_sql: false

UserRepositoryTest.java

package com.jege.spring.boot.data.jpa;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.jege.spring.boot.data.jpa.entity.User;
import com.jege.spring.boot.data.jpa.repository.UserRepository;

/**
 * @author JE哥
 * @email 1272434821@qq.com
 * @description:
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest()
public class UserRepositoryTest {
  @Autowired
  UserRepository userRepository;

  // 打印出class com.sun.proxy.$Proxy66表示spring注入通过jdk动态代理获取接口的子类
  @Test
  public void proxy() throws Exception {
    System.out.println(userRepository.getClass());
  }

  @Test
  public void save() throws Exception {
    for (int i = 0; i < 10; i++) {
      User user = new User("jege" + i, 25 + i);
      userRepository.save(user);
    }
  }

  @Test
  public void all() throws Exception {
    save();
    assertThat(userRepository.findAll()).hasSize(10);
  }

  @Test
  public void findByName() throws Exception {
    save();
    assertThat(userRepository.findByNameLike("jege%")).hasSize(10);
  }

  @After
  public void destroy() throws Exception {
    userRepository.deleteAll();
  }

}

源码地址

https://github.com/je-ge/spring-boot

如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!
微信打赏
支付宝打赏

转载于:https://www.cnblogs.com/je-ge/p/6106748.html

相关文章:

  • python :页面布局 ,后台管理页面之左侧菜单跟着滚动条动
  • 点击状态栏让tableview回到顶部最简单的方法
  • AngularJS 依赖注入
  • sql2000分享 批量建表dev_编号
  • 20162317袁逸灏
  • js curry化
  • 文件的删除
  • oracle数据库中的基本语句
  • 第九次作业
  • 软件测试:心得简介!
  • python笔记常用模块
  • python 时间类型和相互转换
  • ipcs命令
  • JavaScript谁动了你的代码
  • 《Unix环境高级编程》 阅读笔记之三 - 文件I/O
  • .pyc 想到的一些问题
  • canvas 五子棋游戏
  • CSS相对定位
  • HTTP 简介
  • Java比较器对数组,集合排序
  • Java基本数据类型之Number
  • JS 面试题总结
  • Lsb图片隐写
  • MySQL-事务管理(基础)
  • ng6--错误信息小结(持续更新)
  • Puppeteer:浏览器控制器
  • Spark in action on Kubernetes - Playground搭建与架构浅析
  • vue-cli在webpack的配置文件探究
  • 浮动相关
  • 给自己的博客网站加上酷炫的初音未来音乐游戏?
  • 回顾 Swift 多平台移植进度 #2
  • 区块链分支循环
  • 延迟脚本的方式
  • LIGO、Virgo第三轮探测告捷,同时探测到一对黑洞合并产生的引力波事件 ...
  • #微信小程序(布局、渲染层基础知识)
  • (2)关于RabbitMq 的 Topic Exchange 主题交换机
  • (二)构建dubbo分布式平台-平台功能导图
  • (附源码)ssm基于微信小程序的疫苗管理系统 毕业设计 092354
  • (附源码)ssm捐赠救助系统 毕业设计 060945
  • (附源码)计算机毕业设计SSM疫情下的学生出入管理系统
  • (力扣题库)跳跃游戏II(c++)
  • (算法)求1到1亿间的质数或素数
  • (一)pytest自动化测试框架之生成测试报告(mac系统)
  • (原創) 如何解决make kernel时『clock skew detected』的warning? (OS) (Linux)
  • (最全解法)输入一个整数,输出该数二进制表示中1的个数。
  • .NET Entity FrameWork 总结 ,在项目中用处个人感觉不大。适合初级用用,不涉及到与数据库通信。
  • .net framwork4.6操作MySQL报错Character set ‘utf8mb3‘ is not supported 解决方法
  • .NET/C# 的字符串暂存池
  • .net反编译工具
  • 。Net下Windows服务程序开发疑惑
  • @select 怎么写存储过程_你知道select语句和update语句分别是怎么执行的吗?
  • @Transactional类内部访问失效原因详解
  • [AutoSar NVM] 存储架构
  • [c#基础]值类型和引用类型的Equals,==的区别
  • [C++打怪升级]--学习总目录