4 回答

TA貢獻1725條經驗 獲得超8個贊
CrudRepository或者不是設計為沒有一對。JpaRepository<Entity,ID>
您最好創建自定義存儲庫,注入實體管理器并從那里進行查詢:
@Repository
public class CustomNativeRepositoryImpl implements CustomNativeRepository {
@Autowired
private EntityManager entityManager;
@Override
public Object runNativeQuery() {
entityManager.createNativeQuery("myNativeQuery")
.getSingleResult();
}
}

TA貢獻1828條經驗 獲得超13個贊
目前,JPA 中沒有創建僅具有本機或 JPQL/HQL 查詢(使用@Query表示法)的存儲庫的功能。要解決此問題,您可以創建一個虛擬對象以插入到擴展界面中,如下所示:
@Entity
public class RootEntity {
@Id
private Integer id;
}
@Repository
public interface Repository extends JpaRepository<RootEntity, Integer> {
}

TA貢獻1876條經驗 獲得超7個贊
這對我們有用。請參閱實體管理器
https://www.baeldung.com/hibernate-entitymanager
@Repository
public class MyRepository {
@PersistenceContext
EntityManager entityManager;
public void doSomeQuery(){
Query query = entityManager.createNativeQuery("SELECT foo FROM bar");
query.getResultsList()
...
}
}
順便說一句,我不認為這里甚至不需要@Repository注釋。

TA貢獻1825條經驗 獲得超4個贊
您可以使用 注釋您的實現,并獲取實體管理器的實例。@Repository
public interface ProductFilterRepository {
Page<Product> filter(FilterTO filter, Pageable pageable);
}
@Repository
@AllArgsConstructor
public class ProductFilterRepositoryImpl implements ProductFilterRepository {
private final EntityManager em;
@Override
public Page<Product> filter(FilterTO filter, Pageable pageable) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> root = cq.from(Product.class);
List<Predicate> predicates = new ArrayList<>();
if (filter.getPriceMin() != null) {
predicates.add(cb.ge(root.get("price"), filter.getPriceMin()));
}
if (filter.getPriceMax() != null) {
predicates.add(cb.le(root.get("price"), filter.getPriceMax()));
}
if (filter.getBrands() != null && !filter.getBrands().isEmpty()) {
predicates.add(root.get("brand").in(filter.getBrands()));
}
if (filter.getCategories() != null && !filter.getCategories().isEmpty()) {
predicates.add(root.get("category").in(filter.getCategories()));
}
cq.where(predicates.toArray(new Predicate[0]));
TypedQuery<Product> tq = em.createQuery(cq);
tq.setMaxResults(pageable.getPageSize());
tq.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
CriteriaQuery<Long> countCq = cb.createQuery(Long.class);
countCq.select(cb.count(countCq.from(Product.class)));
countCq.where(predicates.toArray(new Predicate[0]));
TypedQuery<Long> countTq = em.createQuery(countCq);
Long count = countTq.getSingleResult();
return new PageImpl<>(tq.getResultList(), pageable, count);
}
}
添加回答
舉報