jpa常用语法

动态拼接

第一种: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)")
第二种:原生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和''空字符串的区别

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();获取数据总数

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%,两边要加%

传入集合

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

传入对象

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

使用JPA的一个坑

1、开启了数据库事务
2、通过EntityManager执行查询,获得返回对象
3、代码业务逻辑处理,其中有对象set属性值的操作
4、没有执行过JPA的save方法或者update语句
5、提交数据库事务,发现数据库中对应的数据更新成了新的属性值

在以上情况下,如果对对象执行了set操作,会直接更新数据库

解决方法:
1.new一个新的对象,然后给它赋值
2.使用BeanUtils.copyProperties()方法复制对象,再进行set操作
  BeanUtils.copyProperties("转换前的类", "转换后的类");  //org.springframework.beans

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表示小数点所占的位数。

创建一个公共的父类

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注解

在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();//表示手动回滚事务
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值