所以,spring-data
进行了一些额外的魔法,有助于处理复杂的查询。一开始会觉得很奇怪,在文档中你可能完全跳过它,但它确实非常强大和有用。
它涉及创建自定义的 Repository
和自定义的 `RepositoryImpl',并告诉 Spring 去哪里找它。这是一个例子:
配置类 - 使用注释指向您的存储库包(现在会自动查找 *Impl
类),指向您仍需的 xml 配置:
@Configuration
@EnableJpaRepositories(basePackages = {"com.examples.repositories"})
@EnableTransactionManagement
public class MyConfiguration {
}
jpa-repositories.xml - 告诉Spring
在哪里找到你的repositories,同时告诉Spring
查找文件名为CustomImpl
的自定义repositories:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<jpa:repositories base-package="com.example.repositories" repository-impl-postfix="CustomImpl" />
</beans>
MyObjectRepository
- 这是您可以放置带注释和未注释的查询方法的位置。请注意此存储库接口如何扩展Custom
:
@Transactional
public interface MyObjectRepository extends JpaRepository<MyObject, Integer>, MyObjectRepositoryCustom {
List<MyObject> findByName(String name);
@Query("select * from my_object where name = ?0 or middle_name = ?0")
List<MyObject> findByFirstNameOrMiddleName(String name);
}
MyObjectRepositoryCustom
- 存储库方法更加复杂,无法通过简单查询或注解来处理:
public interface MyObjectRepositoryCustom {
List<MyObject> findByNameWithWeirdOrdering(String name);
}
MyObjectRepositoryCustomImpl
- 在此处使用自动注入的EntityManager
实现这些方法:
public class MyObjectRepositoryCustomImpl implements MyObjectRepositoryCustom {
@Autowired
private EntityManager entityManager;
public final List<MyObject> findByNameWithWeirdOrdering(String name) {
Query query = query(where("name").is(name));
query.sort().on("whatever", Order.ASC);
return entityManager.find(query, MyObject.class);
}
}
令人惊讶的是,当你执行以下操作时,这一切都会汇聚在一起,来自两个接口(以及你实现的CRUD接口)的方法都会显示出来:
myObjectRepository.
你会看到:
myObjectRepository.save()
myObjectRepository.findAll()
myObjectRepository.findByName()
myObjectRepository.findByFirstNameOrMiddleName()
myObjectRepository.findByNameWithWeirdOrdering()
它确实可以工作。您只需要一个接口来查询数据。spring-data
已经准备好应对大型应用程序了。并且您能将尽可能多的查询封装成简单的方法或者注解,这样会更加优秀。
所有这些都在Spring Data Jpa网站上有记录。