小编典典
当我想使用spring-data创建查询时,请遵循上述算法。
1)是否已经提供的查询
通过弹簧数据等的现有接口CrudRepository,PagingAndSortingRepository,JpaRepository等?
示例:saveAndFlush或findAll方法,更多内容参见docs。
Product product = new Product();
// Setters..
productRepository.saveAndFlush();
2)我可以在方法名称中使用关键字创建方法吗?
示例:count,更多内容在docs中。
@Repository
public interface ProductRepository extends JpaRepository {
Long countByTitle(String title);
List findByTitleLikeAndVisible(String title, boolean visible);
}
3)我可以创建编写JPQL的自定义查询方法吗?
示例:docs。
在这种情况下,spring数据不会尝试使用方法名称中的关键字来创建查询,因此方法名称可以是您想要的任何名称。
@Repository
public interface ProductRepository extends JpaRepository {
@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 findByTitleLikeAndVisibleTrue(@Param("title") String title);
}
4)我想要变量列名还是变量条件? 那么解决方案就是规范。
示例:docs,所以回答
@Repository
public interface ProductRepository extends JpaRepository, JpaSpecificationExecutor {
}
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public List findByColumn(String columnName, Object value) {
return productRepository.find((Root root, CriteriaQuery> query, CriteriaBuilder builder) -> {
return builder.and(builder.equal(root.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 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 findByTitle(String title) {
// em.getTransaction().begin();
String sql = "SELECT p FROM Product p WHERE p.title=:title')";
TypedQuery 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.
@Repository
public interface ProductRepository extends JpaRepository, ProductCategoryRepositoryExt {
}
2020-09-26