[英]How to use JPQL without @Query annotation inside the method?
我想在我的图书租赁项目中使用依赖倒置原理。 之前,我使用了扩展CrudRepository
AccountRepository
,所以我的方法如下所示:
@Query("SELECT CASE WHEN COUNT(account) > 0 THEN true ELSE false END FROM
Account account WHERE account.id =:accountID")
boolean doesAccountExistsWithGivenID(@Param("accountID") int accountID);
我已经创建了AccountRepository
和实现这个存储库的类。 实现接口的类称为PostgreSQLAccountRepository
。 在doesAccountExistsWithGivenID
我想以某种方式查询以获得相同的结果。 它看起来像这样:
package bookrental.account;
import bookrental.bookrentals.BookRentals;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class PostgreSQLAccountRepository implements AccountRepository {
private CrudRepository<Account, Integer> repository;
public PostgreSQLAccountRepository(CrudRepository<Account, Integer> repository) {
this.repository = repository;
}
@Override
public List<BookRentals> getAccountRentalsByGivenID(int accountID) {
//TODO
}
@Override
public void deleteById(Integer id) {
this.repository.deleteById(id);
}
@Override
public List<Account> findAll() {
return (List<Account>) this.repository.findAll();
}
@Override
public boolean doesAccountExistsWithGivenID(int accountID) {
//HERE I WANT TO USE JPQL
}
``}
我不想使用existsByID
,因为我有很多使用 JPQL 的方法,所以我需要知道如何在方法内部实现它。
文档清楚地说明了如何从数据存储库自定义方法: https : //docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations
基本上定义要自CustomizedRepository
的界面片段( CustomizedRepository
)。 在您的数据存储库中扩展此接口
interface SomeRepositry extends CrudRepository<...>, CustomizedRepository
创建名为CustomiyedRepositoryImpl
CustomizedRepository
实现。 Impl
后缀在这里很重要。 有关更多自定义,请参阅文档。
您将需要自动装配SessionFactory
并手动使用它。
@Autowired
public setSessionFactory(EntityManagerFactory factory) {
if(factory.unwrap(SessionFactory.class) == null){
throw new NullPointerException("factory is not a hibernate factory");
}
this.hibernateFactory = factory.unwrap(SessionFactory.class);
}
访问之后就可以直接使用了
Session session = hibernateFactory.createSession();
Query query = session.createQuery("SELECT CASE WHEN COUNT(account) > 0 THEN true ELSE false END FROM Account account WHERE account.id =:accountID");
query.setParameter("accountId", "7277");
List list = query.list();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.