当我想使用spring-data创建查询时,请遵循上述算法。
1)是否已经提供的查询
通过弹簧数据等的现有接口CrudRepository,PagingAndSortingRepository,JpaRepository等?
示例:saveAndFlush或findAll方法,更多内容参见docs。
Product product = new Product();// Setters..productRepository.saveAndFlush();
2)我可以在方法名称中使用关键字创建方法吗?
示例:count,更多内容在docs中。
@Repositorypublic interface ProductRepository extends JpaRepository<Product, Integer> { Long countByTitle(String title); List<Product> findByTitleLikeAndVisible(String title, boolean visible);}3)我可以创建编写JPQL的自定义查询方法吗?
示例:docs。
在这种情况下,spring数据不会尝试使用方法名称中的关键字来创建查询,因此方法名称可以是您想要的任何名称。
@Repositorypublic interface ProductRepository extends JpaRepository<Product, Integer> { @Query("SELECt COUNT(p) FROM Product p WHERe p.title=?1") Long countByTitle(String title); @Query("SELECt p FROM Product p WHERe p.title LIKE :title AND visible=true") List<Product> findByTitleLikeAndVisibleTrue(@Param("title") String title);}4)我想要变量列名还是变量条件? 那么解决方案就是规范。
示例:docs,所以回答
@Repositorypublic interface ProductRepository extends JpaRepository<Product, Integer>, JpaSpecificationExecutor<Product> {}@Servicepublic class ProductService { @Autowired private ProductRepository productRepository; public List<Product> findByColumn(String columnName, Object value) { return productRepository.find((Root<Product> root, CriteriaQuery<?> query, CriteriaBuilder builder) -> { return builder.and(builder.equal(root.<String>get(columnName), value)); }); }}5)我想要更多吗? 解决方案是获取EntityManager并使用它,就像我在没有spring数据库的情况下使用它一样。
(这是对此问题的答案)
示例:so answer,更多文档
// Create an interface and add the methods you wish to use with EntityManger.public interface ProductRepositoryExt { public List<Product> findByTitle(String title);}// Implement the interface you created. Be careful the class name must be identical to the spring-data @Repository interface with the "Impl" appended.public class ProductRepositoryImpl implements ProductRepositoryExt { @PersistenceContext private EntityManager em; @Override public List<Product> findByTitle(String title) {// em.getTransaction().begin(); String sql = "SELECt p FROM Product p WHERe p.title=:title')"; TypedQuery<ProductCategory> query = em.createQuery(sql, Product.class); query.setParameter("title", title); // Add the query hints you wish.. query.setHint(org.eclipse.persistence.config.QueryHints.BATCH_TYPE, "JOIN"); query.setHint(org.eclipse.persistence.config.QueryHints.BATCH, "p.productCategory"); return query.getResultList();// em.getTransaction().commit(); }}// Extend this interface from your spring-data @Repository interface.@Repositorypublic interface ProductRepository extends JpaRepository<Product, Integer>, ProductCategoryRepositoryExt {}


