sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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分页

Repositoryimport 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);
ServicePage<Comment> comments = patientCommentRepository.selectPatientComment(userAccountId,PageRequest.of(page-1, limit, Sort.by(Sort.Direction.DESC, "createDate")));
其中PageRequestPageable的实现类,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
posted on 2023-01-11 13:58  sunny123456  阅读(237)  评论(0编辑  收藏  举报