七、springboot整合Spring-data-jpa

1.Spring Data JPA是什么

  由Spring提供的一个用于简化JPA开发的框架。可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了CRUD外,还包括如分页、排序等一些常用的功能

  Spring Data JPA的核心概念:

1:Repository:最顶层的接口,是一个空的接口,目的是为了统一所有Repository的类型,且能让组件扫描的时候自动识别。

2:CrudRepository :是Repository的子接口,提供CRUD的功能

3:PagingAndSortingRepository:是CrudRepository的子接口,添加分页和排序的功能

4:JpaRepository:是PagingAndSortingRepository的子接口,增加了一些实用的功能,比如:批量操作等。

5:JpaSpecificationExecutor:用来做负责查询的接口

6:Specification:是Spring Data JPA提供的一个查询规范,要做复杂的查询,只需围绕这个规范来设置查询条件即可

具体的关键字,使用方法和生产成SQL如下表所示

Keyword Sample JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection age) … where x.age not in ?1
TRUE findByActiveTrue() … where x.active = true
FALSE findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

2.与springboot整合

  maven:

<dependency
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

  gradle:

dependencies {
        compile('org.springframework.boot:spring-boot-starter-data-jpa')      
}

  注:需要配置数据源

  jpa可选配置

spring.jpa.database=
spring.jpa.show-sql=
spring.jpa.properties=
spring.jpa.generate-ddl=
spring.jpa.open-in-view=
spring.jpa.database-platform=
spring.jpa.hibernate.ddl-auto=
spring.data.jpa.repositories.enabled=
spring.jpa.hibernate.naming-strategy=

3.java代码

@NoRepositoryBean
public interface DAOInterface<T> extends JpaRepository<T, String>, JpaSpecificationExecutor<T> {
    
}
public interface JDCommodityRepository extends DAOInterface<JDCommodityBean> {
    
    /**
     * 分页查询商品
     */
    Page<JDCommodityBean> findAll(Specification<JDCommodityBean> spec, Pageable pageable);
}
@Transactional(rollbackFor = Exception.class)
@Service
public class JDCommodityServiceImpl extends BaseService<JDCommodityBean> implements JDCommodityService {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private JDCommodityRepository jdCommodityRepository;

    @Override
    public Page<JDCommodityBean> getJDCommodityListByPage(Integer pageNum, String name, String goodsCategory) {
        Specification<JDCommodityBean> spec = new Specification<JDCommodityBean>() {

            /**
             * 构造断言
             * 
             * @param root
             *            实体对象引用
             * @param query
             *            规则查询对象
             * @param cb
             *            规则构建对象
             * @return 断言
             */
            @Override
            public Predicate toPredicate(Root<JDCommodityBean> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>(); // 所有的断言集合
                //默认
                predicates.add(cb.equal(root.get("state").as(Integer.class), 1));// 上下架状态 1为上架,0为下架
                predicates.add(cb.equal(root.get("saleState").as(Integer.class), 1));// 是否可售,1:是,0:否
                predicates.add(cb.equal(root.get("isCanVAT").as(Integer.class), 1));// 是否可开增票,1:支持,0:不支持
                predicates.add(cb.le(root.get("price").as(BigDecimal.class), 500));// 价格小于等于500
                //自定义
                // 商品名称
                if(null != name && !"".equals(name) && !"''".equals(name) && name != "") {
                    predicates.add(cb.like(root.get("name").as(String.class), "%" + name + "%"));
                }
                // 商品分类
                if(goodsCategory != null && !"".equals(goodsCategory) && !"''".equals(goodsCategory)) {
                    predicates.add(cb.equal(root.get("goodsCategory").as(String.class), goodsCategory));
                }

                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Pageable pageable = new PageRequest(pageNum - 1, JDCommonConstant.COMMODITY_PAGE_SIZE);// 页码:前端从1开始,jpa从0开始
        Page<JDCommodityBean> page = jdCommodityRepository.findAll(spec, pageable);
        return page;
    }

    @Override
    protected EntityManager getEntityManager() {
        return entityManager;
    }

    @Override
    protected DAOInterface<JDCommodityBean> getDAOInterface() {
        return jdCommodityRepository;
    }

}

猜你喜欢

转载自www.cnblogs.com/soul-wonder/p/8984785.html