springboot-5-整合jpa
- ########
- ##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的更多相关文章
- SpringBoot整合系列-整合JPA
原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9959865.html SpringBoot整合JPA进行数据库开发 步骤 第一步:添加必 ...
- SpringBoot系列之——整合JPA、mysql
一.JPA 1. 概念:JPA顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中. 2. ...
- SpringBoot数据访问(二) SpringBoot整合JPA
JPA简介 Spring Data JPA是Spring Data大家族的一部分,它可以轻松实现基于JPA的存储库.该模块用于增强支持基于JPA的数据访问层,它使我们可以更加容易地构建使用数据访问技术 ...
- SpringBoot+SpringData 整合入门
SpringData概述 SpringData :Spring的一个子项目.用于简化数据库访问,支持NoSQL和关系数据存储.其主要目标是使用数据库的访问变得方便快捷. SpringData 项目所支 ...
- Spring Boot整合JPA、Redis和Swagger2
好久没有总结了,最近也一直在学习.今天就把spring boot与其它技术的整合做个小总结,主要是jpa.redis和swagger2.公司里有用到这些,整合起来也很简单. 首先,新建一个Spring ...
- Spring Boot2(九):整合Jpa的基本使用
一.前言 今天早上看到一篇微信文章,说的是国内普遍用的Mybatis,而国外确普遍用的是Jpa.我之前也看了jpa,发现入门相当容易.jpa对于简单的CRUD支持非常好,开发效率也会比Mybatis高 ...
- Spring Boot 整合 JPA 使用多个数据源
介绍 JPA(Java Persistence API)Java 持久化 API,是 Java 持久化的标准规范,Hibernate 是持久化规范的技术实现,而 Spring Data JPA 是在 ...
- Spring Boot 2.X 如何快速整合jpa?
本文目录 一.JPA介绍二.Spring Data JPA类结构图1.类的结构关系图三.代码实现1.添加对应的Starter2.添加连接数据库的配置3.主要代码 一.JPA介绍 JPA是Java Pe ...
- SpringBoot与整合其他技术
SpringBoot与整合其他技术 5.1 SpringBoot整合Mybatis 5.1.1 添加Mybatis的起步依赖 <!--mybatis起步依赖--> <dependen ...
- 学习SpringBoot,整合全网各种优秀资源,SpringBoot基础,中间件,优质项目,博客资源等,仅供个人学习SpringBoot使用
学习SpringBoot,整合全网各种优秀资源,SpringBoot基础,中间件,优质项目,博客资源等,仅供个人学习SpringBoot使用 一.SpringBoot系列教程 二.SpringBoot ...
随机推荐
- .NET Core 类库中读取appsettings.json
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default&quo ...
- asp.net core 使用identityServer4的密码模式来进行身份认证(一)
IdentityServer4是ASP.NET Core的一个包含OpenID和OAuth 2.0协议的框架.具体Oauth 2.0和openId请百度. 前言本博文适用于前后端分离或者为移动产品来后 ...
- SSRS (一)创建基础报表
ReportService创建基础报表 1.数据库SQL Server2012选择SQL Server Data Tools 2.创建商业智能(BI)项目 选择报表服务器项目 ReportServic ...
- C# RSA加解密和MD5加密
1.RSA加密 /// <summary> /// 加密处理 /// </summary> /// <param name="content"> ...
- c# 协变与抗变
定义 协变:与原始类型转换方向相同的可变性称为协变. 抗变:与派生类型转换方向相同的可变性称为抗变. 补充: 参数是协变的,可以使用派生类对象传入需要基类参数的方法,反之不行 返回值是抗变的,不能使用 ...
- PropertyPlaceHolderConfigurer中的location是不是用错了?
本文由作者张远道授权网易云社区发布. spring中常用PropertyPlaceHolderConfigurer来读取properties配置文件的配置信息.常用的配置方式有两种,一种是使用loca ...
- 廖雪峰Python学习笔记——使用元类
元类(MetaClasses) 元类提供了一个改变Python类行为的有效方式. 元类的定义是“一个类的类”.任何实例是它自己的类都是元类. class demo(object): pass obj ...
- 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 ...
- jenkins 配置。
为了避免在jenkins操作过程中的权限问题. 将安装在/Users/Shared/jenkins目录下的卸载. sudo launchctl unload /Library/LaunchDaemon ...
- 跨域请求之jsonp的实现方式
ajax请求受同源策略影响,不允许进行跨域请求,而script标签src属性中的链接却可以访问跨域的js脚本,利用这个特性,服务端不再返回JSON格式的数据,而是返回一段调用某个函数的js代码,在sr ...