########
##springboot-parent.version: 1.5.
## jdk 1.8
## #######

在整合jpa之前, 先说下mysql

步骤:

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

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

  3), 获取datasource的connection测试

然后, 配置连接池为druid

  1), pom.xml中引入依赖    

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.</version>
</dependency>

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

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

 

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

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

1, 引入依赖

<!-- 整合jpa使用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> <!-- Spring Boot JDBC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> <!--mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

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

application.yml

##### jpa #######
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password:
driver-class-name: com.mysql.jdbc.Driver
jpa:
database: MYSQL
show-sql: true
hibernate:
ddl-auto: update
# naming:
# implicit-strategy: org.hibernate.cfg.ImprovedNamingStrategy
properties: # 默认
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect

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

package com.iwhere.test.demo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

// 生成表结构
@Entity
// 表名, 不写默认为类名
@Table(name="demo")
public class Demo {   // 主键
@Id   // 主键生成策略
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@NotNull
private String name; @Column(nullable=false)
private String sex; public Integer getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setId(Integer id) {
this.id = id;
} }

4, dao层继承接口即可

package com.iwhere.test.dao;

import org.springframework.data.repository.CrudRepository;

import com.iwhere.test.demo.Demo;

/**
* 使用crud接口的dao层
* @author 231
*
*/
public interface DemoRepository extends CrudRepository<Demo, Long> { }

5, service层调用

package com.iwhere.test.service;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.iwhere.test.dao.DemoRepository;
import com.iwhere.test.demo.Demo; /**
* service层
* @author 231
*/
@Service
public class DemoService { @Resource
private DemoRepository demoRepository; @Transactional
public void save(Demo demo) {
demoRepository.save(demo);
} }

6, controller层执行

package com.iwhere.test.web;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.iwhere.test.demo.Demo;
import com.iwhere.test.service.DemoService; @RestController
@RequestMapping("/demo")
public class DemoController { @Resource
private DemoService demoService; /**
* 返回json格式数据
* @RestController
* @return
*/
@RequestMapping("/getDemo")
public Demo getDemo() {
Demo demo = new Demo();
demo.setId();
demo.setName("Angel");
return demo;
} /**
* 测试jpa的使用
* @return
*/
@RequestMapping("/save")
public String saveDemo() {
Demo demo = new Demo();
demo.setId();
demo.setName("Angel");
demo.setSex("female");
demoService.save(demo);
return "ok";
}

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

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

然后,  介绍下repository接口:

1, 空接口, 标记
2, 继承Repository接口后, 会被IOC容器识别为一个bean
3, 也可用@RepositoryDefinition注解来代替继承
4, 方法名即sql语句
5, 条件树形要用关键字链接
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建议做为最后一个参数传入

Page<User> findALL(Pageable pageable);

Page<User> findByUserName(String userName,Pageable pageable);

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

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

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. Vivado级联Modelsim仿真Re-launch问题

    前两天在群里看到有朋友说Vivado级联Modelsim仿真出现修改设计代码后重新run do文件,波形没有随着代码修改而改变,这个问题博主之前没有注意到,因为把Vivado和Modelsim级联好后 ...

  2. Python学习-29.Python中列表的一些操作

    in关键字: 注意这个是关键字,用来判断元素是否在集合中存在. list = ['a','b','c'] print('a' in list) print('f' in list) 将依次输出 Tru ...

  3. wsdl 结构解析

    webservice的跨平台特性要求它必须有某种手段来对服务进行自我描述,使不同的语言能正确理解如何调用该服务.webservice通过WSDL(Web Services Description La ...

  4. [LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )

    Unique Paths https://oj.leetcode.com/problems/unique-paths/ A robot is located at the top-left corne ...

  5. The transaction associated with this command is not the connection's active transaction

    The fix is fairly simple: if you want a Dapper query to participate in a connection, explicitly deno ...

  6. 零开始:NetCore项目权限管理系统:登录授权

    喜欢NetCore的朋友,欢迎加群QQ:86594082 源码地址:https://github.com/feiyit/SoaProJect 管理员的模型 namespace FytSoa.Core. ...

  7. Http请求基本方法

    1.Http请求基本方法 /// <summary> /// Http请求基本方法 /// </summary> /// <param name="conten ...

  8. Backbone学习笔记 - View篇

    Backbone是一种Web端的MVC框架,这里纪录学习Model,View和Collection的笔记. 1 View initialize构造函数 Backbone.View 与jQuery库紧密 ...

  9. 【自动化专题】借助firefox插件定位web元素小技巧

    浏览器:firefox 插件:firebug.firepath.firefinder 安装插件---已安装的请跳过 1.安装firefox浏览器 2.打开firefox-附加组件(找不到入口的问度娘) ...

  10. Disruptor使用简介

    disruptor是lmax公司开发的一款java高性能并发框架,其本质是一种类似队列的实现“生产者—消费者 ”模式的组件. 下面是其示例代码: public class DisruptorServe ...