如何整合spring data jpa

1、pom依赖

		<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

2、添加配置

spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3、创建dto对象

@Entity
public class City implements Serializable { private static final long serialVersionUID = 1L; @Id
@SequenceGenerator(name = "city_generator", sequenceName = "city_sequence", initialValue = 23)
@GeneratedValue(generator = "city_generator")
private Long id; @Column(nullable = false)
private String name; @Column(nullable = false)
private String state; @Column(nullable = false)
private String country; @Column(nullable = false)
private String map;
......
}

4、创建操作数据的Repository对象

public interface CityRepository extends Repository<City, Long> {

	Page<City> findAll(Pageable pageable);

	Page<City> findByNameContainingAndCountryContainingAllIgnoringCase(String name,
String country, Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); }

5、写个简单的Controller触发调用

@Controller
public class CityController { @Autowired
private CityRepository cityRepository; @GetMapping("/")
@ResponseBody
@Transactional(readOnly = true)
public void helloWorld() {
City city = cityRepository.findByNameAndCountryAllIgnoringCase("Bath", "UK");
System.out.println(city); Page<City> cityPage = cityRepository.findAll(new PageRequest(0,
10,
new Sort(Sort.Direction.DESC, "name")));
System.out.println(Arrays.toString(cityPage.getContent().toArray()));
}
}

启动项目后访问http://localhost:8080/,控制台输出:

Bath,Somerset,UK
[Washington,DC,USA, Tokyo,,Japan, Tel Aviv,,Israel, Sydney,New South Wales,Australia, Southampton,Hampshire,UK, San Francisco,CA,USA, Palm Bay,FL,USA, New York,NY,USA, Neuchatel,,Switzerland, Montreal,Quebec,Canada]

到此,一个简单的SpringBoot2.0集成spring-data-jpa就完成了。

spring-data-jpa对一些简单的数据库操作进行了支持。具体的关键字如下:And,Or,Is,Equals,Between,LessThan,LessThanEqual,GreaterThan,GreaterThanEqual,After,Before,IsNull,IsNotNull,NotNull,Like,NotLike,StartingWith,EndingWith,Containing,OrderBy,Not,In,NotIn,TRUE,FALSE,IgnoreCase。spring-data-jpa对这些关键字的支持原理将在源码分析篇讲解,欢迎关注。

如果有复杂一些的sql语句,依靠上面的关键字是肯定不行的,所以spring-data-jpa还提供了注解用来支持自定义sql。在SQL的查询方法上面使用@Query注解,如涉及到删除和修改在需要加上@Modifying。

例:

    @Query("select c from City c where c.id = ?1")
City queryById(long id); @Modifying
@Query("update City c set c.name = ?2 where c.id = ?1")
int updateNameById(long id, String name);

注意:自定义sql的语句是对对象进行操作,风格和hql相似。

SQL数据文件在源码中,源码地址:GitHub


本篇到此结束,如果读完觉得有收获的话,欢迎点赞、关注、加公众号【贰级天災】,查阅更多精彩历史!!!

SpringBoot2.0应用(四):SpringBoot2.0之spring-data-jpa的更多相关文章

  1. Java Spring Boot VS .NetCore (四)数据库操作 Spring Data JPA vs EFCore

    Java Spring Boot VS .NetCore (一)来一个简单的 Hello World Java Spring Boot VS .NetCore (二)实现一个过滤器Filter Jav ...

  2. [每日短篇] 1C - Spring Data JPA (0)

    2019独角兽企业重金招聘Python工程师标准>>> 准备把 Spring Data JPA 完整看一遍,顺便把关键要点记录一下.在写这篇文章的今天,再不用 Spring Boot ...

  3. Spring Data JPA教程,第一部分: Configuration(翻译)

    Spring Data JPA项目旨在简化基于仓库的JPA的创建并减少与数据库交互的所需的代码量.本人在自己的工作和个人爱好项目中已经使用一段时间,它却是是事情如此简单和清洗,现在是时候与你分享我的知 ...

  4. JPA && Spring Data && Spring Data JPA

    1.JPA  Java Persistence API,用于对象持久化的一组API,JPA本身是一组规范,让开发者用同一种方式访问不同的ORM框架.其实也就是java实体对象和关系型数据库建立起映射关 ...

  5. 实例对比 hibernate, spring data jpa, mybatis 选型参考

    原文: 最近重构以前写的服务,最大的一个变动是将mybatis切换为spring data jpa,切换的原因很简单,有两点:第一.它是spring的子项目能够和spring boot很好的融合,没有 ...

  6. javaweb各种框架组合案例(四):maven+spring+springMVC+spring data jpa(hibernate)【失败案例】

    一.失败案例 1. 控制台报错信息 严重: Exception sending context initialized event to listener instance of class org. ...

  7. Spring Data Jpa的四种查询方式

    一.调用接口的方式 1.基本介绍 通过调用接口里的方法查询,需要我们自定义的接口继承Spring Data Jpa规定的接口 public interface UserDao extends JpaR ...

  8. Spring Data JPA教程, 第四部分: JPA Criteria Queries(未翻译)

    The third part of my Spring Data JPA tutorialdescribed how you can create custom queries by using qu ...

  9. Spring Data Jpa (四)注解式查询方法

    详细讲解声明式的查询方法 1 @Query详解 使用命名查询为实体声明查询是一种有效的方法,对于少量查询很有效.一般只需要关心@Query里面的value和nativeQuery的值.使用声明式JPQ ...

  10. spring data jpa开启批量插入、批量更新

    spring data jpa开启批量插入.批量更新 原文链接:https://www.cnblogs.com/blog5277/p/10661096.html 原文作者:博客园--曲高终和寡 *** ...

随机推荐

  1. tensorflow学习之(十一)将python代码写入文件

    #save to file import tensorflow as tf import numpy as np ##(1)Save to file 把相关变量存储到文件中 #remember to ...

  2. unity渲染路径

    (1)      deferred shading:有最佳的光照和阴影效果,在场景中存在许多的实时光照时,使用deferred shading也是最佳的方案,之所以叫做deferred(延迟),是因为 ...

  3. Codeforces Round #538 (Div. 2) CTrailing Loves (or L'oeufs?)

    这题明白的意思就是求n!在b进制下的后缀零的个数. 即最大的n!%(b^k)==0的k的值.我们需要将如果要构成b这个数,肯定是由一个个质因子相乘得到的.我们只需要求出b的质因子,然后分析n!中可以组 ...

  4. JQuery跳出each循环的方法

    一.jquery each循环,要实现break和continue的功能: break----用return false; continue --用return ture; 二.jquery怎么跳出当 ...

  5. nodejs + 小程序云函数 生成小程序码

    前言:这个东西坑死我了 业务需求要生成小程序码 然后我找了两天的资料 运行 生成一堆的乱码 死活就是不能生成 最后看了一遍博客 套用了一下 自己又简单的改了一下  nodejs 我是刚刚接触  有很多 ...

  6. Paper | 深度网络中特征的可迁移性

    目录 1. 核心贡献 2. 实验设置 2.1. 任务设置 2.2. 网络设置 3. 实验结果 4. 启发 论文:How transferable are features in deep neural ...

  7. virtualenv虚拟环境

    1.你听过虚拟环境么? 虚拟:即不真实 环境:即周围的条件 那么到底什么事虚拟环境呢 2.虚拟环境 它是一个虚拟化,从电脑独立开辟出来的环境.通俗的来讲,虚拟环境就是借助虚拟机docker来把一部分内 ...

  8. 基于jmeter的性能测试平台(一)分布式jmeter搭建

    (1)概述 一台windows虚拟机作为controller,3台Linux虚拟机作为agent. 第一步是在所有虚拟机上安装JDK,版本最好是一样的,然后就是下载安装jmeter,网上资料很多这里不 ...

  9. spark随笔

    spark基于RDD成功构建起大数据处理的一体化解决方案,将MappReduce.Streaming.SQL.Machine Learning.Graph Processing等 大数据计算模型统一到 ...

  10. 【Solidity】学习(1)

    string string类型不可以直接通过length读取字符串长度,也不可以直接通过下标直接访问数据元素 使用的方法是:强制类型转换为bytes 其中," " 和‘ ’都可以表 ...