官方文档html
1.根据时间排序时候查询碰见的错误sql
No property desc found for type Date!数据库
出错前写法学习
findAllOrderByCreateTimeDesc测试
修改后写法this
findAllByOrderByCreateTimeDescspa
参考文档:.net
https://stackoverflow.com/questions/19733464/order-by-date-asc-with-spring-datacode
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)
二、保存多个实体:repository.save(Iterable<T> entitys)
三、保存一个实体并当即刷新更改:repository.saveAndFlush(T entity)
注意事项:保存对象时须要肯定 PRIMARY KEY和惟一索引。不然会报出“Duplicate entry '1-2-0' for key”这样的错误。
修改对象时,也使用如上方法,但须要肯定PRIMARY KEY,若是PRIMARY KEY不存在,则是添加操做。
2、@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中)