1. ########
  2. ##springboot-parent.version: 1.5.
  3. ## jdk 1.8
  4. ## #######

在整合jpa之前, 先说下mysql

步骤:

  1), 在application.properties中加入datasource配置

  2), 在pom.xml中加入mysql依赖

  3), 获取datasource的connection测试

然后, 配置连接池为druid

  1), pom.xml中引入依赖    

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>druid</artifactId>
  4. <version>1.0.</version>
  5. </dependency>

  2), 配置application.properties数据源类型

  3), 编写druid servlet和filter提供监控页面访问

 

jpa, 是一种规范, hibernate是他的一种实现方式

jpa是一种关于数据操作的 orm 对象/关系映射规范

1, 引入依赖

  1. <!-- 整合jpa使用 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-jpa</artifactId>
  5. </dependency>
  6.  
  7. <!-- Spring Boot JDBC -->
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-jdbc</artifactId>
  11. </dependency>
  12.  
  13. <!--mysql驱动 -->
  14. <dependency>
  15. <groupId>mysql</groupId>
  16. <artifactId>mysql-connector-java</artifactId>
  17. </dependency>

2, 在src/main/source创建配置文件

application.yml

  1. ##### jpa #######
  2. spring:
  3. datasource:
  4. url: jdbc:mysql://localhost:3306/test
  5. username: root
  6. password:
  7. driver-class-name: com.mysql.jdbc.Driver
  8. jpa:
  9. database: MYSQL
  10. show-sql: true
  11. hibernate:
  12. ddl-auto: update
  13. # naming:
  14. # implicit-strategy: org.hibernate.cfg.ImprovedNamingStrategy
  15. properties: # 默认
  16. hibernate:
  17. dialect: org.hibernate.dialect.MySQL5Dialect

3, 在实体类上加入@Entity, 就可以进行crud操作了

  1. package com.iwhere.test.demo;
  2.  
  3. import javax.persistence.Column;
  4. import javax.persistence.Entity;
  5. import javax.persistence.GeneratedValue;
  6. import javax.persistence.GenerationType;
  7. import javax.persistence.Id;
  8. import javax.persistence.Table;
  9. import javax.validation.constraints.NotNull;

  10. // 生成表结构
  11. @Entity
    // 表名, 不写默认为类名
  12. @Table(name="demo")
  13. public class Demo {
  14.  
  15.   // 主键
  16. @Id
  17.  
  18.   // 主键生成策略
  19. @GeneratedValue(strategy=GenerationType.AUTO)
  20. private Integer id;
  21. @NotNull
  22. private String name;
  23.  
  24. @Column(nullable=false)
  25. private String sex;
  26.  
  27. public Integer getId() {
  28. return id;
  29. }
  30. public void setId(int id) {
  31. this.id = id;
  32. }
  33. public String getName() {
  34. return name;
  35. }
  36. public void setName(String name) {
  37. this.name = name;
  38. }
  39. public String getSex() {
  40. return sex;
  41. }
  42. public void setSex(String sex) {
  43. this.sex = sex;
  44. }
  45. public void setId(Integer id) {
  46. this.id = id;
  47. }
  48.  
  49. }

4, dao层继承接口即可

  1. package com.iwhere.test.dao;
  2.  
  3. import org.springframework.data.repository.CrudRepository;
  4.  
  5. import com.iwhere.test.demo.Demo;
  6.  
  7. /**
  8. * 使用crud接口的dao层
  9. * @author 231
  10. *
  11. */
  12. public interface DemoRepository extends CrudRepository<Demo, Long> {
  13.  
  14. }

5, service层调用

  1. package com.iwhere.test.service;
  2.  
  3. import javax.annotation.Resource;
  4. import org.springframework.stereotype.Service;
  5. import org.springframework.transaction.annotation.Transactional;
  6. import com.iwhere.test.dao.DemoRepository;
  7. import com.iwhere.test.demo.Demo;
  8.  
  9. /**
  10. * service层
  11. * @author 231
  12. */
  13. @Service
  14. public class DemoService {
  15.  
  16. @Resource
  17. private DemoRepository demoRepository;
  18.  
  19. @Transactional
  20. public void save(Demo demo) {
  21. demoRepository.save(demo);
  22. }
  23.  
  24. }

6, controller层执行

  1. package com.iwhere.test.web;
  2.  
  3. import javax.annotation.Resource;
  4.  
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7.  
  8. import com.iwhere.test.demo.Demo;
  9. import com.iwhere.test.service.DemoService;
  10.  
  11. @RestController
  12. @RequestMapping("/demo")
  13. public class DemoController {
  14.  
  15. @Resource
  16. private DemoService demoService;
  17.  
  18. /**
  19. * 返回json格式数据
  20. * @RestController
  21. * @return
  22. */
  23. @RequestMapping("/getDemo")
  24. public Demo getDemo() {
  25. Demo demo = new Demo();
  26. demo.setId();
  27. demo.setName("Angel");
  28. return demo;
  29. }
  30.  
  31. /**
  32. * 测试jpa的使用
  33. * @return
  34. */
  35. @RequestMapping("/save")
  36. public String saveDemo() {
  37. Demo demo = new Demo();
  38. demo.setId();
  39. demo.setName("Angel");
  40. demo.setSex("female");
  41. demoService.save(demo);
  42. return "ok";
  43. }

  44.   /**测试自定义异常*/
  45. // @RequestMapping("/zeroExcetpion")
  46. // public int zeroException() {
  47. // System.err.println("zero");
  48. // return 1/0;
  49. // }
  50. }

此时运行, 既可以在数据库看到demo的存入了

然后,  介绍下repository接口:

  1. 1, 空接口, 标记
  2. 2, 继承Repository接口后, 会被IOC容器识别为一个bean
  3. 3, 也可用@RepositoryDefinition注解来代替继承
  4. 4, 方法名即sql语句
  5. 5, 条件树形要用关键字链接
  6. 6, 可以使用@Query实现自定义jpql语句

jpa操作为接口操作, 一个方法既一个sql语句, 常见的接口如下表:

具体的关键字,使用方法和生产成SQL如下表所示: 原文地址: http://www.cnblogs.com/ityouknow/p/5891443.html

Keyword Sample JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection age) … where x.age not in ?1
TRUE findByActiveTrue() … where x.active = true
FALSE findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

分页查询

分页查询在实际使用中非常普遍了,spring data jpa已经帮我们实现了分页的功能,在查询的方法中,需要传入参数Pageable
,当查询中有多个参数的时候Pageable建议做为最后一个参数传入

  1. Page<User> findALL(Pageable pageable);
  2.  
  3. Page<User> findByUserName(String userName,Pageable pageable);

Pageable 是spring封装的分页实现类,使用的时候需要传入页数、每页条数和排序规则

  1. @Test
  2. public void testPageQuery() throws Exception {
  3. int page=,size=;
  4. Sort sort = new Sort(Direction.DESC, "id");
  5. Pageable pageable = new PageRequest(page, size, sort);
  6. userRepository.findALL(pageable);
  7. userRepository.findByUserName("testName", pageable);
  8. }

springboot-5-整合jpa的更多相关文章

  1. SpringBoot整合系列-整合JPA

    原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9959865.html SpringBoot整合JPA进行数据库开发 步骤 第一步:添加必 ...

  2. SpringBoot系列之——整合JPA、mysql

    一.JPA      1. 概念:JPA顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中. 2. ...

  3. SpringBoot数据访问(二) SpringBoot整合JPA

    JPA简介 Spring Data JPA是Spring Data大家族的一部分,它可以轻松实现基于JPA的存储库.该模块用于增强支持基于JPA的数据访问层,它使我们可以更加容易地构建使用数据访问技术 ...

  4. SpringBoot+SpringData 整合入门

    SpringData概述 SpringData :Spring的一个子项目.用于简化数据库访问,支持NoSQL和关系数据存储.其主要目标是使用数据库的访问变得方便快捷. SpringData 项目所支 ...

  5. Spring Boot整合JPA、Redis和Swagger2

    好久没有总结了,最近也一直在学习.今天就把spring boot与其它技术的整合做个小总结,主要是jpa.redis和swagger2.公司里有用到这些,整合起来也很简单. 首先,新建一个Spring ...

  6. Spring Boot2(九):整合Jpa的基本使用

    一.前言 今天早上看到一篇微信文章,说的是国内普遍用的Mybatis,而国外确普遍用的是Jpa.我之前也看了jpa,发现入门相当容易.jpa对于简单的CRUD支持非常好,开发效率也会比Mybatis高 ...

  7. Spring Boot 整合 JPA 使用多个数据源

    介绍 JPA(Java Persistence API)Java 持久化 API,是 Java 持久化的标准规范,Hibernate 是持久化规范的技术实现,而 Spring Data JPA 是在 ...

  8. Spring Boot 2.X 如何快速整合jpa?

    本文目录 一.JPA介绍二.Spring Data JPA类结构图1.类的结构关系图三.代码实现1.添加对应的Starter2.添加连接数据库的配置3.主要代码 一.JPA介绍 JPA是Java Pe ...

  9. SpringBoot与整合其他技术

    SpringBoot与整合其他技术 5.1 SpringBoot整合Mybatis 5.1.1 添加Mybatis的起步依赖 <!--mybatis起步依赖--> <dependen ...

  10. 学习SpringBoot,整合全网各种优秀资源,SpringBoot基础,中间件,优质项目,博客资源等,仅供个人学习SpringBoot使用

    学习SpringBoot,整合全网各种优秀资源,SpringBoot基础,中间件,优质项目,博客资源等,仅供个人学习SpringBoot使用 一.SpringBoot系列教程 二.SpringBoot ...

随机推荐

  1. .NET Core 类库中读取appsettings.json

    { "Logging": { "IncludeScopes": false, "LogLevel": { "Default&quo ...

  2. asp.net core 使用identityServer4的密码模式来进行身份认证(一)

    IdentityServer4是ASP.NET Core的一个包含OpenID和OAuth 2.0协议的框架.具体Oauth 2.0和openId请百度. 前言本博文适用于前后端分离或者为移动产品来后 ...

  3. SSRS (一)创建基础报表

    ReportService创建基础报表 1.数据库SQL Server2012选择SQL Server Data Tools 2.创建商业智能(BI)项目 选择报表服务器项目 ReportServic ...

  4. C# RSA加解密和MD5加密

    1.RSA加密 /// <summary> /// 加密处理 /// </summary> /// <param name="content"> ...

  5. c# 协变与抗变

    定义 协变:与原始类型转换方向相同的可变性称为协变. 抗变:与派生类型转换方向相同的可变性称为抗变. 补充: 参数是协变的,可以使用派生类对象传入需要基类参数的方法,反之不行 返回值是抗变的,不能使用 ...

  6. PropertyPlaceHolderConfigurer中的location是不是用错了?

    本文由作者张远道授权网易云社区发布. spring中常用PropertyPlaceHolderConfigurer来读取properties配置文件的配置信息.常用的配置方式有两种,一种是使用loca ...

  7. 廖雪峰Python学习笔记——使用元类

    元类(MetaClasses) 元类提供了一个改变Python类行为的有效方式. 元类的定义是“一个类的类”.任何实例是它自己的类都是元类. class demo(object): pass obj ...

  8. 873. Length of Longest Fibonacci Subsequence

    A sequence X_1, X_2, ..., X_n is fibonacci-like if: n >= 3 X_i + X_{i+1} = X_{i+2} for all i + 2 ...

  9. jenkins 配置。

    为了避免在jenkins操作过程中的权限问题. 将安装在/Users/Shared/jenkins目录下的卸载. sudo launchctl unload /Library/LaunchDaemon ...

  10. 跨域请求之jsonp的实现方式

    ajax请求受同源策略影响,不允许进行跨域请求,而script标签src属性中的链接却可以访问跨域的js脚本,利用这个特性,服务端不再返回JSON格式的数据,而是返回一段调用某个函数的js代码,在sr ...