官方文档

https://docs.spring.io/spring-data/jpa/docs/1.11.10.RELEASE/reference/html/

常用关键字

通常,JPA的查询创建机制与Query方法中描述的一样。以下是JPA查询方法转换为的简短示例:

示例45.从方法名称创建查询

public interface UserRepository扩展了Repository <User,Long> {

  List <User> findByEmailAddressAndLastname(String emailAddress,String lastname);

}

我们将使用JPA标准API创建一个查询,但实质上这将转换为以下查询:select u from User u where u.emailAddress = ?1 and u.lastname = ?2

Spring Data JPA将执行属性检查并遍历嵌套属性,如Property表达式中所述。以下是JPA支持的关键字概述以及包含该关键字的方法实际上转换为的内容。

表4.方法名称中支持的关键字
关键词 方法名 JPQL代码段

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

Is,Equals

findByFirstnamefindByFirstnameIsfindByFirstnameEquals

… 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(附加参数绑定%

EndingWith

findByFirstnameEndingWith

… where x.firstname like ?1(与前置绑定的参数%

Containing

findByFirstnameContaining

… where x.firstname like ?1(包含参数绑定%

OrderBy

findByAgeOrderByLastnameDesc

… where x.age = ?1 order by x.lastname desc

Not

findByLastnameNot

… where x.lastname <> ?1

In

findByAgeIn(Collection<Age> ages)

… where x.age in ?1

NotIn

findByAgeNotIn(Collection<Age> ages)

… 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)

 

例子

//查询
public UserEntity findByUserName(String uName); //public List<UserEntity> findByUserName(String uName); //多条件查询
public UserEntity findByUserNameAndPassWord(String uName, String psw); //统计
public long countByUserName(String uName);
//判断存在
public boolean existsByUserName(String uName);
//多条件判断存在
public boolean existsByUserNameAndPassWord(String uName, String psw); //删除等效于SQL
//DELETE u FROM user_info AS u WHERE u.id=?1;
//DELET FROM user_info where id=?1;
public long deleteById(String id);
//in删除,等效于
//DELETE u FROM user_info AS u WHERE u.id IN ?1;
public int deleteByIdIn(List<String> ids) //原生SQL
@Modifying
@Query(value = "DELETE u FROM user_info AS u WHERE u.id=?1 AND u.role not like '%root%'", nativeQuery = true)
public int deleteUser(String id); @Modifying
@Query(value = "DELETE u FROM user_info AS u WHERE u.id IN ?1 AND u.role not like '%root%'", nativeQuery = true)
public int deleteMoreUser(List<String> ids);

起步

1.配置文件

server:
port: 7006
tomcat:
uri-encoding : UTF-8
spring:
profiles:
include: config
application:
name: ams-svc-print
devtools:
restart:
enabled: true #设置热部署启动
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/ams_db?useUnicode=true&characterEncoding=utf8&useSSL=false
username: amsuser
password: ams2018
jpa:
show-sql: true
properties:
hibernate:
hbm2ddl:
auto: update #有多个值create,none
http:
multipart:
maxFileSize: 40Mb #单个文件上传大小限制
maxRequestSize: 40Mb #总上传文件大小限制
#entitymanager:
#packagesToScan: com.entity

#服务发现
eureka:
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://admin:admin@127.0.0.1:7001/eureka/
debug: true

2.pom.xml配置,红字部分

<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.test</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/>
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<!--version>Dalston.SR1</version-->
<version>Edgware.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

<!--添加文件上传进度条支持-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

3.实体层

@Entity
@Table(name = "orderInfo", indexes = { @Index(name = "orderNoIndex", columnList = "orderNo", unique = true) })
public class OrderEntity
{
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id; // id
private String orderNo = CommonUtil.getOrderNO(); // 订单号
private String userName; // 用户名
private String orderState; // 订单状态,未付款, 待发货,已发货,已签收,已完成
@Temporal(TemporalType.TIMESTAMP)
private Date createTime = new Date(); // 下单时间
@Temporal(TemporalType.TIMESTAMP)
private Date finishTime; // 订单完成时间
private String acceptUserName; // 收件人姓名
private String acceptUserPhone; // 收件人电话
private String acceptUserAddress; // 收件人地址
private double totalPrice; // 订单总价
private double totalPayPrice; // 实际支付价格
private boolean needIvoice; // 是否开发票
private String note; // 备注 public String getOrderId()
{
return id;
} public void setOrderId(String orderId)
{
this.id = orderId;
} public String getOrderNo()
{
return orderNo;
} public void setOrderNo(String orderNo)
{
this.orderNo = orderNo;
} public String getUserName()
{
return userName;
} public void setUserName(String userName)
{
this.userName = userName;
} public String getOrderState()
{
return orderState;
} public void setOrderState(String orderState)
{
this.orderState = orderState;
} public Date getCreateTime()
{
return createTime;
} public void setCreateTime(Date createTime)
{
this.createTime = createTime;
} public Date getFinishTime()
{
return finishTime;
} public void setFinishTime(Date finishTime)
{
this.finishTime = finishTime;
} public String getAcceptUserName()
{
return acceptUserName;
} public void setAcceptUserName(String acceptUserName)
{
this.acceptUserName = acceptUserName;
} public String getAcceptUserPhone()
{
return acceptUserPhone;
} public void setAcceptUserPhone(String acceptUserPhone)
{
this.acceptUserPhone = acceptUserPhone;
} public String getAcceptUserAddress()
{
return acceptUserAddress;
} public void setAcceptUserAddress(String acceptUserAddress)
{
this.acceptUserAddress = acceptUserAddress;
} public double getTotalPrice()
{
return totalPrice;
} public void setTotalPrice(double totalPrice)
{
this.totalPrice = totalPrice;
} public double getTotalPayPrice()
{
return totalPayPrice;
} public void setTotalPayPrice(double totalPayPrice)
{
this.totalPayPrice = totalPayPrice;
} public boolean isNeedIvoice()
{
return needIvoice;
} public void setNeedIvoice(boolean needIvoice)
{
this.needIvoice = needIvoice;
} public String getNote()
{
return note;
} public void setNote(String note)
{
this.note = note;
} public OrderEntity()
{
super();
} }

4.访问层

Repository
public interface OrderRepository extends JpaRepository<OrderEntity, String>
{ public OrderEntity findByOrderNo(String orderNo); public long countByOrderNo(String orderNo);
/**
* 更新订单的状态
* @param orderNO
* @param orderState
* @return
*/
@Modifying
@Query(value="update orderInfo set orderState=?2 where orderNo=?1",nativeQuery=true)
public int updateOrderPayState(String orderNO,String orderState);
/**
* 更新订单的支付价格
* @param orderNO
* @param orderState
* @return
*/
@Modifying
@Query(value="update orderInfo set payPrice=?2 where orderNo=?1",nativeQuery=true)
public int updateOrderPayPrice(String orderNO,double payPrice);
/**
* 更新订单的总价
* @param orderNO
* @param orderState
* @return
*/
@Modifying
@Query(value="update orderInfo set totalPrice=?2 where orderNo=?1",nativeQuery=true)
public int updateOrderTotalPrice(String orderNO,double totalPrice); }

springboot JPA mysql的更多相关文章

  1. springboot+jpa+mysql+redis+swagger整合步骤

    springboot+jpa+MySQL+swagger框架搭建好之上再整合redis: 在电脑上先安装redis: 一.在pom.xml中引入redis 二.在application.yml里配置r ...

  2. springboot+jpa+mysql+swagger整合

    Springboot+jpa+MySQL+swagger整合 创建一个springboot web项目 <dependencies> <dependency>      < ...

  3. spring-boot jpa mysql emoji utfmb4 异常处理

    spring-boot jpa mysql utf8mb4 emoji 写入失败 mysql database,table,column 默认为utf8mb4 Caused by: java.sql. ...

  4. IDEA SpringBoot+JPA+MySql+Redis+RabbitMQ 秒杀系统

    先放上github地址:spike-system,可以直接下载完整项目运行测试 SpringBoot+JPA+MySql+Redis+RabbitMQ 秒杀系统 技术栈:SpringBoot, MyS ...

  5. Springboot Jpa: [mysql] java.sql.SQLException: Duplicate entry 'XXX' for key 'PRIMARY'

    前言 1.问题背景 偶尔会出现登录请求出错的情况,一旦失败就会短时间内再也登录不上,更换浏览器或者刷新可能会暂时解决这个问题. 项目运行日志如下: 2022-07-21 09:43:40.946 DE ...

  6. SpringBoot+Jpa+MySql学习

    上一篇介绍了springboot简单整合mybatis的教程.这一篇是介绍springboot简单整合jpa的教程. 由于jpa的功能强大,后续会继续写关于jpa的介绍已经使用,本文只是简单介绍一下它 ...

  7. Springboot+Atomikos+Jpa+Mysql实现JTA分布式事务

    1 前言 之前整理了一个spring+jotm实现的分布式事务实现,但是听说spring3.X后不再支持jotm了,jotm也有好几年没更新了,所以今天整理springboot+Atomikos+jp ...

  8. SpringBoot 使用JPA+MySQL+Thymeleaf 总结 二

    SpringBoot 使用JPA+MySQL+Thymeleaf 总结 一 SpringBoot 使用JPA+MySQL+Thymeleaf 总结 二 方法一 使用原生sql查询 或者 为方法名增加 ...

  9. SpringBoot 使用JPA+MySQL+Thymeleaf 总结 一

    SpringBoot 使用JPA+MySQL+Thymeleaf 总结 一 SpringBoot 使用JPA+MySQL+Thymeleaf 总结 二 pom引用 <?xml version=& ...

随机推荐

  1. HTTP服务器(2)

    import socket import re import multiprocessing def service_client(new_socket): """为这个 ...

  2. DB 分库分表的基本思想和切分策略

    DB 分库分表的基本思想和切分策略 一.基本思想 Sharding的基本思想就要把一个数据库切分成多个部分放到不同的数据库(server)上,从而缓解单一数据库的性能问题.不太严格的讲,对于海量数据的 ...

  3. LeetCode 81. 搜索旋转排序数组 II(Search in Rotated Sorted Array II)

    题目描述 假设按照升序排序的数组在预先未知的某个点上进行了旋转. ( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] ). 编写一个函数来判断给定的目标值是否存在 ...

  4. HearthBuddy的plugin加载

    // Hearthbuddy.Windows.MainWindow // Token: 0x060001FF RID: 511 RVA: 0x0008951C File Offset: 0x00087 ...

  5. [学习笔记] L1-PCA

    L1-PCA Intro PCA的本质就是从高维空间向低维空间投影,投影的本质又是左乘(或右乘)一个向量(表征原来特征空间到投影后特征空间的权重),经过线性加权,转换到低维空间表征,如果将向量换成矩阵 ...

  6. 3.MapReduce原理和Yarn

    1.MapReduce原理 2.MapReduce执行时间 3.MapReduce开发 4.Yarn

  7. LC 861. Score After Flipping Matrix

    We have a two dimensional matrix A where each value is 0 or 1. A move consists of choosing any row o ...

  8. LoaderDialog自定义加载框的实现

    package com.loaderman.loadingdialogdemo; import android.app.Dialog; import android.content.Context; ...

  9. Popover 弹出框

    基础用法 Popover 的属性与 Tooltip 很类似,它们都是基于Vue-popper开发的,因此对于重复属性,请参考 Tooltip 的文档,在此文档中不做详尽解释. 设置索引ref,在按钮中 ...

  10. Oracle安装过程中Oracle Database Configuration Assistant失败问题解决

    今天在安装Oracle的过程中出现了oracle Database Configuration Assistant问题,我解决该问题的方法是将我的计算机用户名更改了一下,改成了pc1.之后再在orac ...