JPA 开发写SQL时候遇见的困难点

官方文档

https://docs.spring.io/spring-data/jpa/docs/1.11.16.RELEASE/reference/html/#repositories.special-parameters

1.根据时间排序时候查询遇见的错误

No property desc found for type Date!

出错前写法

findAllOrderByCreateTimeDesc

修改后写法

findAllByOrderByCreateTimeDesc

参考文档:

https://stackoverflow.com/questions/19733464/order-by-date-asc-with-spring-data

2.JPA自定义sql注意

@Query

使用自定义sql报错:

Validation failed for query for method public abstract

解决方法如下:

必须全是对象的值包括查询条件或者:

原生sql必须加nativeQuery=true

@Query(value = "select count(1) from collect_orders o where o.tier_two_seller_id=?1",nativeQuery=true)

Long queryAllOrderCount(Long id);

3.JPA保存数据的一些坑

当调用JPA的save方法时候如果没有为id设置自增的时候就会报错:

ids for this class must be manually assigned before calling save()

解决办法:

必须在主键get方法上要加上

@GeneratedValue(strategy = GenerationType.AUTO)

或

@GeneratedValue(strategy = GenerationType.IDENTITY)

4.JPA其他一些操作 保存数据 修改数据

参考博客:地址

SpringDataJpa进行修改数据库操作有两种方式:

一、调用保存实体的方法

1、保存一个实体:repository.save(T entity)

2、保存多个实体:repository.save(Iterable<T> entitys)

3、保存一个实体并立即刷新更改:repository.saveAndFlush(T entity)

注意事项:保存对象时需要确定 PRIMARY KEY和唯一索引。否则会报出“Duplicate entry '1-2-0' for key”这样的错误。

    修改对象时,也使用如上方法,但需要确定PRIMARY KEY,如果PRIMARY KEY不存在,则是添加操作。

二、@Query注解(写JPQL语句)

JPQL( Java 持久性查询语言)JPQL 和 SQL 的主要区别在于,前者处理JPA 实体、属性,后者直接在数据库空间内对表、列、行等关系数据进行处理。

JPQL解释:https://blog.csdn.net/qq_33746131/article/details/56479226

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.jpa.repository.Modifying;

import org.springframework.data.jpa.repository.Query;

import org.springframework.data.repository.query.Param;

import org.springframework.transaction.annotation.Transactional;

Repositoryk中@Query写JPQL语句:@Query("JPQL语句")

 例1 修改操作

@Modifying

@Transactional

@Query("update CityStationGoods csg set csg.isOnsale = ?2 where csg.id = ?1")

int updateOnSaleState(int id, Boolean isOnsale);

例2  使用参数下标

@Modifying

@Transactional

@Query("delete from GoodsActivity ga where ga.activityId = ?1")

void deleteByActivityId(Integer activityId);

例3  使用参数名

@Modifying

@Transactional

@Query("delete from GoodsActivity ga where ga.activityId = :id")

void deleteByActivityId(@Param(value = "id")Integer activityId);

Repositoryk中@Query写SQL语句:@Query(value="SQL语句",nativeQuery = true)

例1

@Query(value = "SELECT IFNULL(SUM(num),0) FROM shopping_cart WHERE member_id =?1", nativeQuery = true)

int getCartNum(Integer memberId);

注意事项:查询时不需要@Modifying注解。@Modifying:指示方法应被视为修改查询。

            @Transactional注解:在update或delete时,需要事务提交。如果不写Transactional无法将修改后的操作保存到数据库中。该注解可以写在Service或Repository中。(本例因测试学习,写到了Repository中)  

原文地址:https://www.cnblogs.com/shenyanrushang/p/10852499.html