问题
我正在研究Spring Data JPA。考虑下面的示例,我将默认使用所有crud和finder功能,如果我想自定义查找器,那么也可以在界面本身轻松完成。
@Transactional(readOnly = true)
public interface AccountRepository extends JpaRepository<Account, Long> {
@Query("<JPQ statement here>")
List<Account> findByCustomer(Customer customer);
}
我想知道如何为上述AccountRepository添加一个完整的自定义方法及其实现?由于它的接口我无法在那里实现该方法。
#1 热门回答(197 赞)
你需要为自定义方法创建单独的界面:
public interface AccountRepository
extends JpaRepository<Account, Long>, AccountRepositoryCustom { ... }
public interface AccountRepositoryCustom {
public void customMethod();
}
并为该接口提供实现类:
public class AccountRepositoryImpl implements AccountRepositoryCustom {
@Autowired
AccountRepository accountRepository; /* Optional - if you need it */
public void customMethod() { ... }
}
另请参阅:- 4.6 Spring数据存储库的自定义实现
#2 热门回答(62 赞)
除了axtavt'sanswer之外,如果你需要构建查询,请不要忘记你可以在自定义实现中注入Entity Manager:
public class AccountRepositoryImpl implements AccountRepositoryCustom {
@PersistenceContext
private EntityManager em;
public void customMethod() {
...
em.createQuery(yourCriteria);
...
}
}
#3 热门回答(10 赞)
这在使用上受到限制,但对于简单的自定义方法,你可以使用默认的接口方法,如:
import demo.database.Customer;
import org.springframework.data.repository.CrudRepository;
public interface CustomerService extends CrudRepository<Customer, Long> {
default void addSomeCustomers() {
Customer[] customers = {
new Customer("Józef", "Nowak", "nowakJ@o2.pl", 679856885, "Rzeszów", "Podkarpackie", "35-061", "Zamknięta 12"),
new Customer("Adrian", "Mularczyk", "adii333@wp.pl", 867569344, "Krosno", "Podkarpackie", "32-442", "Hynka 3/16"),
new Customer("Kazimierz", "Dejna", "sobieski22@weebly.com", 996435876, "Jarosław", "Podkarpackie", "25-122", "Korotyńskiego 11"),
new Customer("Celina", "Dykiel", "celina.dykiel39@yahoo.org", 947845734, "Żywiec", "Śląskie", "54-333", "Polna 29")
};
for (Customer customer : customers) {
save(customer);
}
}
}
编辑:
在this spring教程中写道:
Spring Data JPA还允许你通过简单地声明其方法签名来定义其他查询方法。
所以甚至可以只声明方法:
Customer findByHobby(Hobby personHobby);
如果objectHobby
是Customer的属性,那么Spring将自动为你定义方法。