06-二次开发教程-DAO-v8

2018-03-20 11:03 阅读

Dao使用了SpringDataJPA技术。技术细节请浏览SpringDataJPA官网:http://projects.spring.io/spring-data-jpa/

配置文件

系统的DAO在com.jspxcms.core.ContextConfig@EnableJpaRepositories(basePackages = {"com.jspxcms.core.repository", "com.jspxcms.ext.repository"}, repositoryFactoryBeanClass = MyJpaRepositoryFactoryBean.class)配置。

本例的DAO在com.jspxcms.plug.ContextConfig@EnableJpaRepositories(basePackages = { "com.jspxcms.plug.repository" }, repositoryFactoryBeanClass = MyJpaRepositoryFactoryBean.class)配置。

DAO类

package com.jspxcms.plug.repository;

public interface ResumeDao extends Repository<Resume, Integer>, ResumeDaoPlus {
    public Page<Resume> findAll(Specification<Resume> spec, Pageable pageable);

    public List<Resume> findAll(Specification<Resume> spec, Limitable limitable);

    public Resume findOne(Integer id);

    public Resume save(Resume bean);

    public void delete(Resume bean);

    @Modifying
    @Query("delete from Resume bean where bean.site.id in (?1)")
    public int deleteBySiteId(Collection<Integer> siteIds);
}

ResumeDao接口中的方法不用实现。以下接口中的方法均可放到ResumeDao,且无需实现:

  • org.springframework.data.repository.CrudRepository
  • org.springframework.data.repository.PagingAndSortingRepository
  • org.springframework.data.jpa.repository.JpaRepository
  • com.jspxcms.common.orm.MyJpaRepository

其中public int deleteBySiteId(Collection<Integer> siteIds);方法并不在这些接口中,则需要使用@Query("delete from Resume bean where bean.site.id in (?1)")指定SQL语句,由于该SQL会修改数据库的数据,所以要加上@Modifying

需要实现的dao方法,放到ResumeDaoPlus接口中。规则是在DAO类名后加上Plus。如DAO类名是AbcDao,则Plus的类名为AbcDaoPlus

package com.jspxcms.plug.repository;

public interface ResumeDaoPlus {
    public List<Resume> getList(Integer[] siteId, Limitable limitable);
}

ResumeDaoPlus接口的实现类要放到对应的impl包中。

package com.jspxcms.plug.repository.impl;

public class ResumeDaoImpl implements ResumeDaoPlus {
    @SuppressWarnings("unchecked")
    public List<Resume> getList(Integer[] siteId, Limitable limitable) {
        JpqlBuilder jpql = new JpqlBuilder();
        jpql.append("from Resume bean where 1=1");
        if (ArrayUtils.isNotEmpty(siteId)) {
            jpql.append(" and bean.site.id in (:siteId)");
            jpql.setParameter("siteId", Arrays.asList(siteId));
        }
        return jpql.list(em, limitable);
    }

    private EntityManager em;
    @PersistenceContext
    public void setEm(EntityManager em) {
        this.em = em;
    }
}

其中com.jspxcms.common.orm.JpqlBuilder用于拼装jqpl语句、设置参数,并可处理分页问题。

咨询
交流群
电话