如果我们想拓展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> {}
第三种方式的拓展就非常强大了,在一个方法里面可以想干什么就干什么了,执行多个语句,执行存储过程等。另外上述三种方式是可以结合在一起使用的,并不冲突。