使用新的Spring Data Evans版本时,很高兴能够使用Java 8附带的一些不错的东西。其中之一是接口中的默认实现。下面的存储库使用QueryDSL来确保查询类型的安全。
我的问题是,在我写这篇文章之前,我先UserRepositoryCustom
为findByLogin
另一个类使用了一个单独的接口模式,然后UserRepositoryImpl
在该类中使用@PersistenceContext
来获取当前值EntityManager
。
EntityManager
我没课时如何获得?可能吗
@Repository
public interface UserRepository extends JpaRepository<User, UUID> {
final QUser qUser = QUser.user;
// How do I get the entityManager since this is a interface, i cannot have any variables?
//@PersistenceContext
//EntityManager entityManager;
public default Optional<User> findByLogin(String login) {
JPAQuery query = new JPAQuery(entityManager);
User user = query
.from(qUser)
.where(
qUser.deleter.isNull(),
qUser.locked.isFalse(),
qUser.login.equalsIgnoreCase(login)
)
.singleResult(qUser);
return Optional.ofNullable(user);
}
}
默认方法仅应用于将调用委派给其他存储库方法。默认方法-根据定义-无法访问实例的任何状态(因为接口没有状态)。它们只能委托给其他接口方法或调用其他类的静态方法。
实际上,使用参考文档中描述的自定义实现是正确的方法。这是供参考的简短版本(如果其他人也想知道的话):
/**
* Interface for methods you want to implement manually.
*/
interface UserRepositoryCustom {
Optional<User> findByLogin(String login);
}
/**
* Implementation of exactly these methods.
*/
class UserRepositoryImpl extends QueryDslRepositorySupport implements UserRepositoryCustom {
private static final QUser USER = QUser.user;
@Override
public Optional<User> findByLogin(String login) {
return Optional.ofNullable(
from(USER).
where(
USER.deleter.isNull(),
USER.locked.isFalse(),
USER.login.equalsIgnoreCase(login)).
singleResult(USER));
}
}
/**
* The main repository interface extending the custom one so that the manually
* implemented methods get "pulled" into the API.
*/
public interface UserRepository extends UserRepositoryCustom,
CrudRepository<User, Long> { … }
请注意,命名约定在这里很重要(但可以根据需要进行自定义)。通过扩展,QueryDslRepositorySupport
您可以访问该from(…)
方法,从而不必与EntityManager
自己进行交互。
或者,您可以从存储库外部UserRepository
实现QueryDslPredicateExecutor
并上交谓词,但这最终会导致需要使用Querydsl的客户端(这可能是不必要的),而且您不会获得Optional
OOTB 的包装类型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句