spring data jpa自定义DAO处理

如果我们想拓展spring data jpa的CrudRepository或PagingAndSortingRepository,加入我们自己的database操作。分3个级别的拓展:

1、继承CrudRepository或PagingAndSortingRepository,在继承的就扣定义findBy**类似的方法。这种方式只能做到最简单的拓展,毕竟一个方法名能表达的意思有限,(就好比我们说一句话能表达的意思也很有限)。

2、使用@Query注解继承接口里面的方法,定义方法要执行的sql,注意方法的每个参数对应sql里的“1?”、“2?”、……参数。这种方法比上一种方法能完成更多的拓展,可以连表,定义子查询等,但是还是只能执行一个sql语句。

3、使用@NoRepositoryBean,定义非仓库bean:

@NoRepositoryBean
interface BaseRepository<T> extends CrudRepository<T, Long> {

	long customMethod();
}

实现上面的接口里定义的方法
/**
 * @author Oliver Gierke
 * @soundtrack Elen - Nobody Else (Elen)
 */
class ExtendedJpaRepository<T> extends SimpleJpaRepository<T, Long> implements BaseRepository<T> {

	/**
	 * Creates a new {@link ExtendedJpaRepository} for the given {@link JpaEntityInformation} and {@link EntityManager}.
	 * 
	 * @param entityInformation must not be {@literal null}.
	 * @param entityManager must not be {@literal null}.
	 */
	public ExtendedJpaRepository(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
		super(entityInformation, entityManager);
	}

	/* 
	 * (non-Javadoc)
	 * @see example.springdata.jpa.customall.BaseRepository#customMethod()
	 */
	@Override
	public long customMethod() {
                //do some database operation
		return 0;
	}
}
最后定义我们的仓库bean接口,让这个接口继承我们新的仓库接口而不是CrudRepository或PagingAndSortingRepository

public interface UserRepository extends BaseRepository<User> {}
第三种方式的拓展就非常强大了,在一个方法里面可以想干什么就干什么了,执行多个语句,执行存储过程等。另外上述三种方式是可以结合在一起使用的,并不冲突。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值