平台访问数据库采用JPA+Hibernate,总共有三种方式:
1、通过平台提供JdbcUtils类直接执行SQL·
@Autowired private JdbcUtils jdbcUtils; public int getCount(){ try{ return jdbcUtils.queryForInt("select count(*) from sdk_example"); } catch(Exception e){ CommonsUtil.recordLog(e); return 0; } }
2、建立DAO类(需扩展BaseDAO)
@Repository public interface sdkExampleDAO extends BaseDAO<sdkExampleBO,String> { //---------通过HSQL访问------------- @Query(value="select bo from sdkExampleBO bo where bo.name =:name") public List<sdkExampleBO> findInfoByHSQL(@Param("name") String name); //---------通过原生SQL访问------------- @Query(value="select r.* from sdk_example r where r.name =:name",nativeQuery = true) public List<sdkExampleBO> findInfoBySQL(@Param("name") String name); }
其中又分两种HQL和原生SQL
另外BaseDAO中也封装了基本操作,如save、delete等,除了使用@Query注解,也可以利用JPA的简化定义方法,例如findAllBy***And***OrderBy***
3、 使用EntityManager
@PersistenceContext private EntityManager entityManager; public Page<ParameterBO> getParameterList(parameterRequestDto dto) { Pageable pageable = PageRequest.of(dto.getPage(), dto.getSize()); String hql="select r from ParameterBO r where 1=1"; String countsql="select count(*) from sys_parameters where 1=1 "; //进行条件组合 if (dto.getParakey()!=null && !"".equals(dto.getParakey())){ countsql+=" and para_key like '%"+dto.getParakey()+"%'"; hql+="and r.parakey like '%"+dto.getParakey()+"%'"; } if (dto.getParaname()!=null && !"".equals(dto.getParaname())){ countsql+=" and para_name like '%"+dto.getParaname()+"%'"; hql+="and r.paraname like '%"+dto.getParaname()+"%'"; } int count =jdbcUtils.queryForInt(countsql); //获取数据 Query query = entityManager.createQuery(hql); query.setFirstResult((int)pageable.getOffset()); query.setMaxResults(pageable.getPageSize()); List<ParameterBO> objArray = query.getResultList(); return new PageImpl<ParameterBO>(objArray,pageable,count); }