4 回答

TA貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
CrudRepository或者不是設(shè)計(jì)為沒(méi)有一對(duì)。JpaRepository<Entity,ID>
您最好創(chuàng)建自定義存儲(chǔ)庫(kù),注入實(shí)體管理器并從那里進(jìn)行查詢:
@Repository
public class CustomNativeRepositoryImpl implements CustomNativeRepository {
@Autowired
private EntityManager entityManager;
@Override
public Object runNativeQuery() {
entityManager.createNativeQuery("myNativeQuery")
.getSingleResult();
}
}

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

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊
這對(duì)我們有用。請(qǐng)參閱實(shí)體管理器
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()
...
}
}
順便說(shuō)一句,我不認(rèn)為這里甚至不需要@Repository注釋。

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以使用 注釋您的實(shí)現(xiàn),并獲取實(shí)體管理器的實(shí)例。@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);
}
}
添加回答
舉報(bào)