首页 > 数据库 >jpa常用语法简单使用 第一种:JPQL 第二种:原生sql

jpa常用语法简单使用 第一种:JPQL 第二种:原生sql

时间:2023-01-11 14:13:15浏览次数:59  
标签:name jpa sql String import JPQL id persistence 属性

jpa常用语法
https://blog.csdn.net/weixin_44758923/article/details/127965476

动态拼接

第一种:JPQL
@Query("select d from Doctor d where (?1 is null or ?1='' or d.deptId=?1) and (?2 is null  or ?2='' or d.admissionsState=?2)")
  • 1
  • 2
第二种:原生sql
@Query(value = "SELECT su.* from sys_user su where if(?3 !='',su.username LIKE %?3% ,1=1) and if(?4 !='',su.realname LIKE %?4% ,1=1) and if(?5 !='',su.create_date=?5 ,1=1) limit ?1,?2",nativeQuery = true)
需要注意null和''空字符串的区别
  • 1
  • 2
  • 3
  • 4

JPQL分页

Repository层
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
@Query(value = "select c from Comment c where c.userAccountId=?1")
Page<Comment> selectPatientComment(Integer userAccountId,Pageable pageable);
Service层
Page<Comment> comments = patientCommentRepository.selectPatientComment(userAccountId,PageRequest.of(page-1, limit, Sort.by(Sort.Direction.DESC, "createDate")));
其中PageRequest是Pageable的实现类,Sort.by指定排序方式和排序字段,因为这里默认是从0开始的,所以要-1
comments.getContent();获取列表数据
comments.getTotalElements();获取数据总数
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

JPQL模糊查询

   @Query("select i from InquiryOrder i where i.userAccountId=?1 and i.patientName like %?2% or i.inquiryOrderSerial like %?2% or i.transactionId like %?2% and i.createDate between ?3 and ?4")
   List<InquiryOrder> userSearch(Integer userAccountId,String name, String startTime, String endTime);
   注意 like %?2%,两边要加%号
  • 1
  • 2
  • 3
  • 4

传入集合

@Query(value = "from User u where u.name in :nameList")
List<User> findByNameIn(@Param("nameList")Collection<String> nameList);
@Query(value = "select i from InquiryOrder i where i.inquiryOrderState in (?1)")
List<InquiryOrder> findInquiryOrder(List<String> list);
原生SQL
SELECT * FROM user WHERE uid IN (2,3,5)
等价于
SELECT * FROM user WHERE (uid=2 OR uid=3 OR uid=5)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

传入对象

@Query(value = "from User u where u.name=:#{#usr.name} and u.password=:#{#usr.password}")
User findByNameAndPassword(@Param("usr")User usr);
  • 1
  • 2

使用JPA的一个坑

1、开启了数据库事务
2、通过EntityManager执行查询,获得返回对象
3、代码业务逻辑处理,其中有对象set属性值的操作
4、没有执行过JPA的save方法或者update语句
5、提交数据库事务,发现数据库中对应的数据更新成了新的属性值
在以上情况下,如果对对象执行了set操作,会直接更新数据库
解决方法:
1.new一个新的对象,然后给它赋值
2.使用BeanUtils.copyProperties()方法复制对象,再进行set操作
  BeanUtils.copyProperties("转换前的类", "转换后的类");  //org.springframework.beans
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

JPA常用注解

javax.persistence
@Id//指定id
@Column(name = "id")//字段名
@GeneratedValue(strategy = GenerationType.IDENTITY)//设置自增长
例如
@Column(nullable = false,columnDefinition = "varchar(100) default '' comment '字段注释...'")
//字段不能为null,类型为varchar,长度100,comment为注释
@Transient表示这个字段不会被添加到数据库
@Column注解一共有10个属性,这10个属性均为可选属性,各属性含义分别如下:
name
name属性定义了被标注字段在数据库表中所对应字段的名称;
unique
unique属性表示该字段是否为唯一标识,默认为false。如果表中有一个字段需要唯一标识,则既可以使用该标记,也可以使用@Table标记中的@UniqueConstraint。
nullable
nullable属性表示该字段是否可以为null值,默认为true。
insertable
insertable属性表示在使用“INSERT”脚本插入数据时,是否需要插入该字段的值。
updatable
updatable属性表示在使用“UPDATE”脚本插入数据时,是否需要更新该字段的值。insertable和updatable属性一般多用于只读的属性,例如主键和外键等。这些字段的值通常是自动生成的。
columnDefinition
columnDefinition属性表示创建表时,该字段创建的SQL语句,一般用于通过Entity生成表定义时使用。(也就是说,如果DB中表已经建好,该属性没有必要使用。)
table
table属性定义了包含当前字段的表名。
length
length属性表示字段的长度,当字段的类型为varchar时,该属性才有效,默认为255个字符。
precision和scale
precision属性和scale属性表示精度,当字段类型为double时,precision表示数值的总长度,scale表示小数点所占的位数。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

创建一个公共的父类

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;
@MappedSuperclass//@MappedSuperclass注解,通过这个注解,我们可以将该实体类当成基类实体,它不会映射到数据库表,但继承它的子类实体在映射时会自动扫描该基类实体的映射属性,添加到子类实体的对应数据库表中。
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)//@Inheritance的strategy属性是指定继承关系的生成策略。TABLE_PER_CLASS是为每一个类创建一个表,这些表是相互独立的
public abstract class Basemodel implements Serializable{
	@Id
	@Column(name = "id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	protected Integer id;
	@Column(name = "create_date", insertable = true, updatable = false, length = 29)
	private String createDate;
	@Column(name = "modify_date", insertable = true, updatable = true, length = 29)
	private String modifyDate;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getCreateDate() {
		return createDate;
	}
	public void setCreateDate(String createDate) {
		this.createDate = createDate;
	}
	public String getModifyDate() {
		return modifyDate;
	}
	public void setModifyDate(String modifyDate) {
		this.modifyDate = modifyDate;
	}
}
//其他实体类只需要继承这个类,就具有了自增长的主键id和创建时间及修改时间的字段,如果有其他公共的字段也可以添加进来。其他类需要要@Entity和@Table注解
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50

在SpringBoot中开启事务回滚

首先在application.properties配置文件中加入
spring.jpa.show-sql = false
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect =org.hibernate.dialect.MySQL5Dialect
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
然后在service方法上面加上@Transactional(rollbackFor = Exception.class)
出现异常时需要在catch里面加上TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//表示手动回滚事务
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

标签:name,jpa,sql,String,import,JPQL,id,persistence,属性
From: https://www.cnblogs.com/sunny3158/p/17043521.html

相关文章

  • tdsql 开源pg版编译文件 tbase
    https://www.aliyundrive.com/s/V6LnixwJG3V这是一个自解压文件,打开后是一个tar.gz压缩文件对应文档中/data/tbase/install/下的文件在centos7下编译不保证可用,以源......
  • MySql基础-笔记2 -数据库创建、删除、选择等操作
    在MySql数据库基础1-Windows下安装配置图文教程的基础上,我们来了解如何对数据库进行操作,比如常见的创建数据库、删除数据库、选择数据库等;(目录)1、连接数据库简单的方......
  • PostgreSQL 中匹配逗号分隔的ID字符串, array,string_to_array,any 的应用
    PostgreSQL中匹配逗号分隔的ID字符串,array,string_to_array,any的应用场景:两张表,books和tags表,一个book对应多个tag。但是book把tag信息存在一个字符串中,用逗......
  • sqlserver 新建连接服务器
         USE[master]GO/******Object:LinkedServer[TEST]ScriptDate:2023-1-1110:50:26******/EXECmaster.dbo.sp_addlinkedserver@server=N......
  • Docker 打包MySQL (带数据源打包) 并加载打包后镜像运行
    前言mysql镜像的数据默认都在/var/lib/mysql目录下,我们修改默认的数据库的数据位置就行,不要放在/var/lib/mysql下面。操作1.创建mysql源数据备份目录mkdir/mysqldata......
  • SQL Server如何查看SQL Server服务启动时间
    SQLServer数据库中,我们想查看SQLServer实例的启动时间以及SQLServerAgent服务的启动时间,有哪一些方法和技巧呢?下面总结一些查看SQLServer实例和SQLServerAgent服务......
  • mysql 备份定时任务
    #!/bin/bashrq=`date+%Y-%m-%d-%H`#日期#数据库信息host=127.0.0.1user=rootpassword=xxxdbname=script#放在这个目录path=/usr/local/backups/sqlmysqldump-h......
  • mysql导出表数据
    -T表-B备份数据库-t线程数-r多少行-c压缩输出文件--less-locking在InnoDB表使用最小的锁表时间导出表结构mydumper-h127.0.0.1-uroot-p*-Btest-t......
  • 实训体会--swing和mysql的使用
    结构设计思想:前端界面和后端数据库通过一个中间件操作。中间件就像一个中间助手,每一个前端界面通过一个具象的中间助手进行操作。最大的设计错误:中间件不是一个具象的实......
  • Redis-01-初见NoSQL
    目录1.为什么要用NoSQL2.什么是NoSQL?2.1NotOnlyStructuredQueryLanguage2.2Nosql特点2.3传统的RDBMS(关系型数据库)2.4Nosql2.5Nosql的四大分类2.5.1KV键值......