SpringData是简化持久层的代码量通过@Query(‘SQL’)来实现接口方法的增删改查
1.继承抽象类Repository
2.定义持久层接口 定义方法
3.通过@Query实现持久操作
4.注意SQL语句在此叫JPQL语句,JPQL不支持INSERT插入语句
public interface UserDao extends Repository<AccountInfo, Long> {
@Query("select a from AccountInfo a where a.accountId = ?1")
public AccountInfo findByAccountId(Long accountId);
@Query("select a from AccountInfo a where a.balance > ?1")
public Page<AccountInfo> findByBalanceGreaterThan(
Integer balance,Pageable pageable);
}
查询条件参数指定
语句中通过": 变量"的格式来指定参数,同时在方法的参数前面使用 @Param 将方法参数与 JP QL 中的命名参数对应。
查询使用属性
public interface UserDao extends Repository<AccountInfo, Long> {
public AccountInfo save(AccountInfo accountInfo);
@Query("from AccountInfo a where a.accountId = :id")
public AccountInfo findByAccountId(@Param("id")Long accountId);
@Query("from AccountInfo a where a.balance > :balance")
public Page<AccountInfo> findByBalanceGreaterThan(
@Param("balance")Integer balance,Pageable pageable);
}
使用 @Query 来执行一个更新操作
用 @Modifying 来将该操作标识为修改查询,这样框架最终会生成一个更新的操作,而非查询
Spring Data JPA 对事务的支持
针对查询类型的方法,其等价于 @Transactional(readOnly=true);增删改类型的方法,等价于 @Transactional。可以看出,除了将查询的方法设为只读事务外,其他事务属性均采用默认值。