基于JPA封装的BaseService

SpringBoot JPA: 打造通用的持久化层 1. 基本操作步骤 1.1 依赖 pom.xml <dependencies> <!-- spring data jpa --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> 阅读详情

JPA-快速开始

我们将通过一个简单的 Demo 来阐述 BaseService 的强大功能,在此之前,我们假设您已经:

  • 拥有 Java 开发环境以及相应 IDE
  • 熟悉 Spring Boot
  • 熟悉 Maven

配置

在 xxxService 类上继承BaseService:

@Service
public class TestService extends BaseService<Merchant> {

}

(单表)获取一条数据

  • getSingleEntityById()方法:

::: tip

  • 源码方法 :
  • T getSingleEntityById(Serializable id)
  • R getSingleEntityById(Class<R> tClass, Serializable id)
    :::
    /**
     * 根据Id获取一条数据 (返回类型为当前注入的实体类型)
     * @param id
     * @return Merchant
     */
    public Merchant getMerchantById(long id){
        return this.getSingleEntityById(id);
    }

    /**
     * 根据Id获取一条数据 (返回类型为自定义传入的实体类型)
     * @param id
     * @return Platform
     */
    public Platform getPlatformById(int id){
        return this.getSingleEntityById(Platform.class, id);
    }

::: tip
参数Id可以是继承Serializable的任意类型,因为BaseService里的方法参数是泛型
:::

  • 根据Sql语句查询一条数据:

::: tip

  • 源码方法 :
  • Long getSingleValue(String sql)
  • Long getSingleValue(String sql, Object params)
  • T getSingleEntity(String sql)
  • R getSingleEntity(Class<R> tClass, String sql)
  • Map<String, Object> getSingleMap(String sql)
    :::
    /**
     * 根据Sql获取一条数据 (返回类型为当前注入的实体类型)
     * @return Merchant
     */
    public Merchant getMerchantBySql(){
        /**
         * Sql构造器 (SqlWrapper)
         */
        String selSql = SqlWrapper.create(Merchant.class).build();
        /**
         * select * from merchant limit 1;
         */
        return this.getSingleEntity(selSql);
    }

    /**
     * 根据Sql获取一条数据 (返回类型为自定义传入的实体类型)
     * @return Platform
     */
    public Platform getPlatformBySql(){
        /**
         * Sql构造器 (SqlWrapper)
         */
        String selSql = SqlWrapper.create().build(Platform.class);
        /**
         * select * from platform limit 1;
         */
        return this.getSingleEntity(Platform.class, selSql);
    }

    /**
     * 根据Sql获取一条数据 (返回类型为当前注入的实体类型)
     * @return Merchant
     */
    public Merchant getMerchantBySqlWithCondition(String name, String merchantNo){
        /**
         * Sql构造器 (SqlWrapper)
         */
        String selSql = SqlWrapper.create(Merchant.class)
                .like(StrUtil.isNotEmpty(name), "merchant_name", name)
                .where(StrUtil.isNotEmpty(merchantNo), "merchant_no", merchantNo)
                .build();
        /**
         * select * from merchant
         * where merchant_name like '%name%'
         * and merchant_no = 'merchantNo'
         * limit 1;
         */
        return this.getSingleEntity(selSql);
    }


    /**
     * 根据Sql获取一条数据 (返回类型为Map类型)
     * @return Map<String, Object>
     */
    public Map<String, Object> getOrderRefundRecordBySqlWithCondition(String orderId, String merchantTradeOrderId){
        /**
         * Sql构造器 (SqlWrapper)
         */
        String selSql = SqlWrapper.create(OrderRefundRecord.class)
                .like(StrUtil.isNotEmpty(orderId), "order_id", orderId)
                .where(StrUtil.isNotEmpty(merchantTradeOrderId), "merchant_trade_order_id", merchantTradeOrderId)
                .build();
        /**
         * select * from t_order_refund_record
         * where order_id like '%orderId%'
         * and merchant_trade_order_id = 'merchantTradeOrderId'
         * limit 1;
         */
        return this.getSingleMap(selSql);
    }


    /**
     * 根据Sql获取单独一个字段,如:平均数、总和、总条数
     * @return Long
     */
    public Long getSingleValueBySqlWithCondition(){
        /**
         * Sql构造器 (SqlWrapper)
         */
        String selSql = SqlWrapper.create(MerchantInfo.class)
                .selectMax("version")
                .build();
        /**
         * select Max(version) from t_merchant_info
         */
        return this.getSingleValue(selSql);
    }

::: tip
SQLWrapper构造器还有很多高级用法,但只能用于单表的Sql拼接,暂时不支持多表联查
:::

(单表)获取AllList集合

  • getAllListEntity()方法:

::: tip

  • 源码方法 :
  • List<Map<String, Object>> getAllListMap()
  • List<Map<String, Object>> getAllListMap(Class<R> tClass)
  • List<T> getAllListEntity()
  • List<R> getAllListEntity(Class<R> tClass)
    :::
    /**
     * 获取表中所有数据 (返回类型为当前注入的实体类型)
     * @return List<Merchant>
     */
    public List<Merchant> getAllMerchantList(){
        return this.getAllListEntity();
    }

    /**
     * 获取表中所有数据 (返回类型为自定义传入的实体类型)
     * @return List<BankChannel>
     */
    public List<BankChannel> getAllBankChannelList(){
        return this.getAllListEntity(BankChannel.class);
    }

    /**
     * 获取表中所有数据 (返回类型为当前注入的实体类型)
     * @return List<Map<String, Object>>
     */
    public List<Map<String, Object>> getAllMerchantListMap(){
        return this.getAllListMap();
    }

    /**
     * 获取表中所有数据 (返回类型为自定义传入的实体类型)
     * @return List<Map<String, Object>>
     */
    public List<Map<String, Object>> getAllBankChannelListMap(){
        return this.getAllListMap(BankChannel.class);
    }
  

::: tip
几乎所有的方法都有两套,默认第一个参数是Class类型,
如果不传,那么就取当前继承BaseService时传入的实体类型,如果传递就取自定义的实体类型
:::

(单表)根据Sql获取List集合

  • getListEntity()方法:

::: tip

  • 源码方法 :

  • List<T> getListEntity(String sql)

  • List<T> getListEntity(String sql, Object params)

  • List<T> getListEntity(String sql, Pageable pageable)

  • List<T> getListEntity(String sql, Object params, Pageable pageable)

  • Page<T> getPagedListEntity(String sql, Pageable pageable)

  • Page<T> getPagedListEntity(String sql, Object params, Pageable pageable)

  • List<R> getListEntity(Class<R> tClass, String sql)

  • List<R> getListEntity(Class<R> tClass, String sql, Object params)

  • List<R> getListEntity(Class<R> tClass, String sql, Pageable pageable)

  • List<R> getListEntity(Class<R> tClass, String sql, Object params, Pageable pageable)

  • Page<R> getPagedListEntity(Class<R> tClass, String sql, Pageable pageable)

  • Page<R> getPagedListEntity(Class<R> tClass, String sql, Object params, Pageable pageable)
    :::

   /**
    * Sql构造器 (SqlWrapper)
    */
   String selSql = SqlWrapper.create(BuryingPoint.class)
           //.select("id, content")
           .where("id >", 1)
           .where("name !=", "777")
           .orWhere("description !=", "777")
           .like(StrUtil.isNotEmpty("实体店"), "name", "实体店")
           .orLike(StrUtil.isNotEmpty("实体店"), "type", "实体店")
           .orGroupStart()
               .like("name", "yyyyyy")
           .groupEnd()
           .groupStart()
               .where("name !=", "777")
               .orWhere("description !=", "777")
           .groupEnd()
           .orderBy("id", "desc")
           .orderBy("name", "asc")
           .groupBy("name")
           .build();
           /*
           SELECT
               *
           FROM
               `burying_point`
           WHERE
               `id` > 1
               AND `name` != '777'
               OR `description` != '777'
               AND `name` LIKE '%实体店%' ESCAPE '!'
               OR `type` LIKE '%实体店%' ESCAPE '!'
               OR ( `name` LIKE '%yyyyyy%' ESCAPE '!' )
               AND ( `name` != '777' OR `description` != '777' )
           GROUP BY
               `name`
           ORDER BY
               `id` DESC,
               `name` ASC
           */
    /**
     * 根据Sql查询List返回 (返回类型为自定义传入的"BuryingPoint"实体类型)
      */
    List<BuryingPoint> merchantListEntity = this.getListEntity(BuryingPoint.class, selSql);

    /**
     *  取分页List数据 (返回List)
     */
    Pageable pageable = PageRequest.of(0, 10);
    List<BuryingPoint> pagedListEntity = this.getListEntity(BuryingPoint.class, selSql, pageable);


    /**
     *  取分页List数据 (返回List<Map<String, Object>>)
     */
    List<Map<String, Object>> pagedListMap = this.getListMap(selSql, pageable);

::: tip
几乎所有的方法都有两套,默认第一个参数是Class类型,
如果不传,那么就取当前继承BaseService时传入的实体类型,如果传递就取自定义的实体类型
:::

  • getPagedListEntity()方法 / 获取分页数据并返回分页对象:

::: tip

  • 源码方法 :
  • Page<T> getPagedListEntity(String sql, Pageable pageable)
  • Page<T> getPagedListEntity(String sql, Object params, Pageable pageable)
  • Page<R> getPagedListEntity(Class<R> tClass, String sql, Pageable pageable)
  • Page<R> getPagedListEntity(Class<R> tClass, String sql, Object params, Pageable pageable)
    :::
   Pageable pageable = PageRequest.of(0, 10);
   /**
   *  取分页List数据 (返回Page<Map<String, Object>>)
   */
  Page<Map<String, Object>> pagedModelListMap = this.getPagedListMap(selSql, pageable);


  /**
   *  取分页List数据 (返回Page<Merchant>)
   */
  Page<Merchant> pagedCurrentEntityList = this.getPagedListEntity(selSql, pageable);


  /**
   *  取分页List数据 (返回Page<BuryingPoint>)
   */
  Page<BuryingPoint> pagedBuryingPointEntityList = this.getPagedListEntity(BuryingPoint.class, selSql, pageable);     

::: tip
分页方法只需要传递一个正常的Sql就可以,无需关心查总条数(Count)Sql,因为方法里封装了取数据总条数的Sql,详情请看getCount(sql)方法
:::

保存数据方法

  • save()、saveBatch()、saveAndFlush()方法:

::: tip

  • 源码方法 :
  • Boolean save(T entity)
  • Boolean saveAndFlush(T entity)
  • Boolean saveBatch(Collection<T> listEntities)
  • Boolean save(Class<R> tClass, R entity, boolean... isAutoFlush)
  • Boolean saveAndFlush(Class<R> tClass, R entity)
  • Boolean saveBatch(Class<R> tClass, Collection<R> listEntities)
    :::
     /**
      * 创建当前Service泛型注入的对象并赋值
      */
     Merchant merchant = new Merchant();
     merchant.setIdPlat(6L);
     merchant.setMerchantName("特朗普的小店");
     merchant.setMerchantNo("VIP000666");
     merchant.setVipCardNuber("CARD000666");

     /**
      * 保存一条数据并返回数据Id
      */
     boolean saveRetId = this.save(merchant);


     /**
      * 创建自定义的对象并赋值
      */
     BuryingPoint buryingPoint = new BuryingPoint();
     buryingPoint.setName("消费V1");
     buryingPoint.setDescription("xx描述");
     buryingPoint.setContent("xx内容");
     buryingPoint.setType("V1");
     buryingPoint.setBuryingKey("BP_Key");

     /**
      * 保存自定义的对象一条数据并返回数据Id
      */
     boolean saveOtherRetId = this.save(BuryingPoint.class, buryingPoint);

     /**
      * 创建当前Service泛型注入的对象集合并模拟赋值
      */
     List<Merchant> merchantList = new ArrayList<>();
     for (int i = 0; i < 20 ; i++) {
         Merchant interMerchant = new Merchant();
         interMerchant.setIdPlat(6L);
         interMerchant.setMerchantName("特朗普的小店" + Convert.toStr(i));
         interMerchant.setMerchantNo("VIP000666" + Convert.toStr(i));
         interMerchant.setVipCardNuber("CARD000666" + Convert.toStr(i));
         merchantList.add(interMerchant);
     }

     /**
      * 保存多条数据并返回Bool
      */
     boolean saveStatus = this.saveBatch(merchantList);          
     
     /**
      * 保存多条数据并返回Bool (保存自定义类型,具体就不多赘述了)
      */
     boolean saveOtherStatus = this.saveBatch(Merchant.class, merchantList); 

::: tip
如果需要flush,请使用带flush后缀的方法
:::

更新数据方法

  • updateById()、updateBatch()、updateByIdAndFlush()方法:

::: tip

  • 源码方法 :
  • Boolean updateById(Serializable id, T entity)
  • Boolean updateById(Class<R> tClass, Serializable id, R entity, boolean... isAutoFlush)
  • Boolean updateByIdAndFlush(Serializable id, T entity)
  • Boolean updateByIdAndFlush(Class<R> tClass, Serializable id, R entity)
  • Boolean updateBatch(Collection<T> listEntities)
    :::
    /**
     * 根据Id更新实体 (当前Service泛型注入的对象)
     */
    boolean merchantUpdateStatus = this.updateById(merchant.getId(), merchant);


    /**
     * 根据Id更新实体 (自定义类型对象更新)
     */
    boolean buryingPointUpdateStatus = this.updateById(BuryingPoint.class, buryingPoint.getId(), buryingPoint);


    /**
     * 更新多条数据 (当前Service泛型注入的对象)
     */
    boolean merUpdateBatchStatus = this.updateBatch(merchantList);


    /**
     * 更新多条数据 (自定义类型对象集合) / 同save方法一致,不多赘述
     */
    boolean burUpdateBatchStatus = this.updateBatch(BuryingPoint.class, buryingPointList);            

::: tip
update方法和save方法一致
:::

保存或更新数据

  • saveOrUpdate()方法:
    ::: tip
  • 源码方法 :
  • Boolean saveOrUpdate(T entity)
  • Boolean saveOrUpdateAndFlush(T entity)
  • Boolean saveOrUpdate(Class<R> tClass, R entity, boolean... isAutoFlush)
  • Boolean saveOrUpdateAndFlush(Class<R> tClass, R entity)
    :::
    /**
     * 保存或者更新一条记录 (当前Service泛型注入的泛型类型)
     */
    Boolean saveOrUpdateId = this.saveOrUpdate(merchant);

    /**
     * 保存或者更新一条记录 (自定义类型对象更新)
     */
    Boolean burSaveOrUpdateId = this.saveOrUpdate(BuryingPoint.class, buryingPoint);               

::: tip
保存或更新方法,底层会根据传入的实体主键Id判断是保存还是更新
:::

(公用)获取数据总条数方法

::: tip
不用手动拼接Select Count(0)语法,getCount方法中会自动拼接为: (SELECT COUNT(0) COUNT_NUM FROM (" + sql + ") AS TOTAL)
所以参数只需要传递正常查数据的Sql就可以, 使用方法如下:
:::

  • (单表) getCount()方法:
    /**
     * Sql构造器
     */
    String bankCountSql = SqlWrapper.create(BankChannel.class).build();
    /**
     * 根据Sql查询数据条数
     */
    long bankCount = this.getCount(bankCountSql);
  • (多表) getCount()方法:
    /**
    * 手动构建Sql语句 + 参数
    */
   String recordSql = "SELECT\n" +
           "\t* \n" +
           "FROM\n" +
           "\tt_trade_payment_record,\n" +
           "\tmerchant \n" +
           "WHERE\n" +
           "\t1 = 1 \n" +
           "\tAND t_trade_payment_record.id = merchant.id\n" +
           "\tAND t_trade_payment_record.bank_channel_name LIKE :channelName \n" +
           "\tAND t_trade_payment_record.bank_order_no LIKE :orderNo ";

   Map<String, Object> recordParams = new HashMap<>();
   recordParams.put("channelName", "%中xxxx微信%");
   recordParams.put("orderNo", "YLH%");

   /**
    * 根据Sql + 参数查询数据条数
    */
   long recordCount = this.getCount(recordSql, recordParams);   

(公用)根据Sql查询一列数据

::: tip

  • 注意事项
    1. 第一个参数是你要查询的这一列对应java里的数据类型,比如Id,数据库是bigint那么可以传递Long.class, 返回List<Long>
    1. 不区分多表和单表,只要保证查出来的是一列就可以
      :::
     /**
     * Sql构造器 构建查询一列Sql
     */
    String idListSql = SqlWrapper.create(Merchant.class).select("Id").build();

    /**
     * 根据sql查询一列数据 返回List<>
     */
    List<Long> singleColumnList = this.getSingleColumnList(Long.class, idListSql);  
    
    /**
     * 手动构建多表联合查询Sql
     */
    String singleColSql = "select m.int_1 from merchant m LEFT JOIN company c on m.id = c.company_id";

    /**
     * 根据sql查询一列数据 返回List<>
     */
    List<Boolean> singleColSqlList = this.getSingleColumnList(Boolean.class, singleColSql); 

(多表联合)获取List或者Page<>的方法

::: tip
所有的getList或者getPagedList开头的方法都支持手动拼接sql传入,用法和单表的一致,以下只做简单的示范:
:::

  • (多表) getListEntity()和getPagedListEntity()方法:
   /**
    * 手动构建Sql语句 + 参数
    */
   String unionSql = "SELECT\n" +
           "\t* \n" +
           "FROM\n" +
           "\tt_trade_payment_record,\n" +
           "\tmerchant \n" +
           "WHERE\n" +
           "\t1 = 1 \n" +
           "\tAND t_trade_payment_record.id = merchant.id\n" +
           "\tAND t_trade_payment_record.bank_channel_name LIKE :channelName \n" +
           "\tAND t_trade_payment_record.bank_order_no LIKE :orderNo ";

   Map<String, Object> unionSqlParams = new HashMap<>();
   unionSqlParams.put("channelName", "%中投科信微信%");
   unionSqlParams.put("orderNo", "YLH%");

   /**
    * 根据自定义多表关联Sql + 参数查询返回Map
    */
   List<Map<String, Object>> unionListMap = this.getListMap(unionSql, unionSqlParams);

   /**
    * 根据自定义多表关联Sql + 参数查询返回List<CoustomXXXModel>
    */
   List<CoustomXXXModel> unionListEntity = this.getListEntity(CoustomXXXModel.class, unionSql, unionSqlParams);

   /**
    * 根据自定义多表关联Sql + 参数查询返回Page<Map<String, Object>>
    */
   Page<Map<String, Object>> pagedListMap1 = this.getPagedListMap(unionSql, unionSqlParams, pageable);

   /**
    * 根据自定义多表关联Sql + 参数查询返回Page<CoustomXXXModel>
    */
   Page<CoustomXXXModel> pageListEntityCus = this.getPagedListEntity(CoustomXXXModel.class, unionSql, unionSqlParams, pageable);

#BaseService源代码

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class BaseService<T> extends BeetlSqlCoreService<T>{

    @PersistenceContext
    protected EntityManager em;


    protected final static Long DEFAULT_ID_ERROR_VALUE = -1L;

    protected final static String FIELD_UNDERSCORE_NAME = "_";

    /**
     * 默认Id字段名,如果根据实体查不到id字段,默认返回这个
     */
    protected final static String DEFAULT_ID_NAME = "id";


    /**
     * 获取SqlWrapper对象
     * @return SqlWrapper
     */
    public SqlWrapper japQuery(){
        return this.japQuery(this.getCurrentTClass());
    }

    public <R> SqlWrapper japQuery(Class<R> targetClass) {
        return SqlWrapper.create(targetClass);
    }

    /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓(Select查询部分)基于EntityManager的CreateNativeQuery↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/

    /**
     * 根据sql查询一个值 (取一个值,如:平均数,最大值,最小值, 总数)
     * @author: wei.fu
     * @param sqlOrSqlId
     * @return long
     */
    public Long jpaGetSingleValue(String sqlOrSqlId){
       return this.jpaGetSingleValue(sqlOrSqlId, null);
    }

    /**
     * 根据sql+参数查询一个值 (取一个值,如:平均数,最大值,最小值, 总数)
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @return Long
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Long jpaGetSingleValue(String sqlOrSqlId, Map<String, Object> params){
        try {
            /**
             * 验证sql是否符合规范
             */
            String[] conditions = new String[]{","};
            if(!this.validatorSqlSpec(sqlOrSqlId, conditions)){
                throw new Exception("Sql: '"+ sqlOrSqlId +"' 传入的Sql语句包含多列,请检查Sql重新调用此方法");
            }
            Query query = this.buildQuery(sqlOrSqlId, params, null, false);
            Object singleResult = query.getSingleResult();
            return Convert.toLong(singleResult, DEFAULT_ID_ERROR_VALUE);
        } catch (Exception e) {
            log.error("BaseService.jpaGetSingleValue 异常:" + e.getMessage(), e);
        }finally{
            em.close();
        }
        return DEFAULT_ID_ERROR_VALUE;
    }



    /**
     * 根据sql查询一条记录
     * @author: wei.fu
     * @param sqlOrSqlId
     * @return Map<String, Object>
     */
    public T jpaGetSingleEntity(String sqlOrSqlId){
       Map<String, Object> objectMap = this.jpaGetSingleMap(sqlOrSqlId);
       T entity = BeanUtil.mapToBean(objectMap, this.getCurrentTClass(), true);
       this.mergeLostFields(entity, objectMap);
       return entity;
    }

    /**
     * 根据sql查询一条记录
     * @author: wei.fu
     * @param sqlOrSqlId
     * @return Map<String, Object>
     */
    public <R> R jpaGetSingleEntity(Class<R> tClass, String sqlOrSqlId){
        Map<String, Object> objectMap = this.jpaGetSingleMap(sqlOrSqlId);
        R entity = BeanUtil.mapToBean(objectMap, tClass, true);
        this.mergeLostFields(entity, objectMap);
        return entity;
    }


    /**
     * 根据sql查询一条记录
     * @author: wei.fu
     * @param sqlOrSqlId
     * @return Map<String, Object>
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Map<String, Object> jpaGetSingleMap(String sqlOrSqlId){
        Query query = this.buildQuery(sqlOrSqlId);
        /**
         * 起始对象位置
         */
        query.setFirstResult(0);
        /**
         * 查询对象个数
         */
        query.setMaxResults(1);

        Map<String, Object> resultMap = MapUtil.createMap(HashMap.class);
        try {
            List<Map<String, Object>> resultList = query.getResultList();
            return Linq.asEnumerable(resultList).firstOrDefault();
        } catch (Exception e) {
            log.error("BaseService.jpaGetSingleMap 异常:" + e.getMessage(), e);
        }finally{
            em.close();
        }
        return resultMap;
    }

    /**
     * 根据Sql和分页参数查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param pageable (分页对象)
     * @return List<Map<String, Object>>
     */
    public List<Map<String, Object>> jpaGetListMap(String sqlOrSqlId, Pageable pageable){
        return this.jpaGetListMap(sqlOrSqlId, null, pageable);
    }

    /**
     * 根据Sql查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @return List<Map<String, Object>>
     */
    public List<Map<String, Object>> jpaGetListMap(String sqlOrSqlId){
        return this.jpaGetListMap(sqlOrSqlId, null, null);
    }

    /**
     * 根据Sql和参数查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @return List<Map<String, Object>>
     */
    public List<Map<String, Object>> jpaGetListMap(String sqlOrSqlId, Map<String, Object> params){
        return this.jpaGetListMap(sqlOrSqlId, params, null);
    }

    /**
     * 根据Sql和分页参数查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @param pageable
     * @return List<Map<String, Object>>
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<Map<String, Object>> jpaGetListMap(String sqlOrSqlId, Map<String, Object> params, Pageable pageable){
        Query query = this.buildQuery(sqlOrSqlId, params, pageable);
        List<Map<String, Object>> resultList=new ArrayList<>();
        try {
            resultList=query.getResultList();
        } catch (Exception e) {
            log.error("BaseService.jpaGetListMap 异常:" + e.getMessage(), e);
            return resultList;
        }finally{
            em.close();
        }
        return resultList;
    }

    /**
     * 根据SQL语句查询返回分页对象
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param pageable
     * @return Page<Map<String, Object>>
     */
    public Page<Map<String, Object>> jpaGetPagedListMap(String sqlOrSqlId, Pageable pageable){
        return this.jpaGetPagedListMap(sqlOrSqlId, null, pageable);
    }

    /**
     * 根据SQL+参数查询返回分页对象
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @param pageable
     * @return Page<Map>
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Page<Map<String, Object>> jpaGetPagedListMap(String sqlOrSqlId, Map<String, Object> params, Pageable pageable){
        Page<Map<String, Object>> pageModel = null;
        long totalCount = 0;

        Query query = this.buildQuery(sqlOrSqlId, params, pageable);

        List<Map<String, Object>> resultList=new ArrayList<>();
        /**
         * 获取数据总条数
         */
        totalCount = this.jpaGetCount(sqlOrSqlId, params);
        try {
            resultList=query.getResultList();
            if(Validator.isNotNull(pageable) && pageable.getPageNumber() > 0){
                pageable = PageRequest.of(pageable.getPageNumber()-1, pageable.getPageSize());
            }
            pageModel = new PageImpl<>(resultList, pageable, totalCount);
        } catch (Exception e) {
            log.error("BaseService.jpaGetPagedListMap 异常:" + e.getMessage(), e);
        }finally{
            em.close();
        }
        return pageModel;
    }

    /**
     * 根据Sql和分页参数查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param pageable (分页对象)
     * @return List<Map<String, Object>>
     */
    public List<T> jpaGetListEntity(String sqlOrSqlId, Pageable pageable){
        return this.jpaGetListEntity(sqlOrSqlId, null, pageable);
    }

    /**
     * 根据Sql查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @return List<Map<String, Object>>
     */
    public List<T> jpaGetListEntity(String sqlOrSqlId){
        return this.jpaGetListEntity(sqlOrSqlId, null, null);
    }

    /**
     * 根据Sql和参数查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @return List<Map<String, Object>>
     */
    public List<T> jpaGetListEntity(String sqlOrSqlId, Map<String, Object> params){
        return this.jpaGetListEntity(sqlOrSqlId, params, null);
    }

    /**
     * 根据Sql和分页参数查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @param pageable
     * @return List<T>
     */
    @SuppressWarnings("unchecked")
    public List<T> jpaGetListEntity(String sqlOrSqlId, Map<String, Object> params, Pageable pageable){
        Query query = this.buildQuery(sqlOrSqlId, params, pageable);
        List<T> resultList=new ArrayList<>();
        try {
            List<Map<String, Object>> resultListMap = query.getResultList();
            resultList = Convert.toList(this.getCurrentTClass(), resultListMap);
            this.mergeLostFields(resultList, resultListMap);
        } catch (Exception e) {
            log.error("BaseService.jpaGetListEntity 异常:" + e.getMessage(), e);
        }finally{
            em.close();
        }
        return resultList;
    }

    /**
     * 根据SQL语句查询返回分页对象
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param pageable
     * @return Page<T>
     */
    public Page<T> jpaGetPagedListEntity(String sqlOrSqlId, Pageable pageable){
        return this.jpaGetPagedListEntity(sqlOrSqlId, null, pageable);
    }


    /**
     * 根据SQL+参数查询返回分页对象
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @param pageable
     * @return Page<T>
     */
    public Page<T> jpaGetPagedListEntity(String sqlOrSqlId, Map<String, Object> params, Pageable pageable){
        return this.jpaGetPagedListEntity(this.getCurrentTClass(), sqlOrSqlId, params, pageable);
    }


    /**
     * 根据Sql和分页参数查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param pageable (分页对象)
     * @return List<R>
     */
    public <R> List<R> jpaGetListEntity(Class<R> tClass, String sqlOrSqlId, Pageable pageable){
        return this.jpaGetListEntity(tClass, sqlOrSqlId, null, pageable);
    }


    /**
     * 根据Sql查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @return List<R>
     */
    public <R> List<R> jpaGetListEntity(Class<R> tClass, String sqlOrSqlId){
        return this.jpaGetListEntity(tClass, sqlOrSqlId, null, null);
    }

    /**
     * 根据Sql和参数查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @return List<R>
     */
    public <R> List<R> jpaGetListEntity(Class<R> tClass, String sqlOrSqlId, Map<String, Object> params){
        return this.jpaGetListEntity(tClass, sqlOrSqlId, params, null);
    }

    /**
     * 根据Sql和分页参数查询列表
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @param pageable
     * @return List<R>
     */
    public <R> List<R> jpaGetListEntity(Class<R> tClass, String sqlOrSqlId, Map<String, Object> params, Pageable pageable){
        List<Map<String, Object>> listMap = this.jpaGetListMap(sqlOrSqlId, params, pageable);
        List<R> resList = Convert.toList(tClass, listMap);
        this.mergeLostFields(resList, listMap);
        return resList;
    }


    /**
     * 根据SQL语句查询返回分页对象
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param pageable
     * @return Page<R>
     */
    public <R> Page<R> jpaGetPagedListEntity(Class<R> tClass, String sqlOrSqlId, Pageable pageable){
        return this.jpaGetPagedListEntity(tClass, sqlOrSqlId, null, pageable);
    }

    /**
     * 根据SQL+参数查询返回分页对象
     * @author: wei.fu
     * @param tClass
     * @param sqlOrSqlId
     * @param params
     * @param pageable
     * @return Page<R>
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public <R> Page<R> jpaGetPagedListEntity(Class<R> tClass, String sqlOrSqlId, Map<String, Object> params, Pageable pageable){
        Page<R> pageModel = null;
        Page<Map<String, Object>> pagedListMap = this.jpaGetPagedListMap(sqlOrSqlId, params, pageable);
        List<R> resultList = Convert.toList(tClass, pagedListMap.getContent());
        this.mergeLostFields(resultList, pagedListMap.getContent());
        if(Validator.isNotNull(pageable) && pageable.getPageNumber() > 0){
            pageable = PageRequest.of(pageable.getPageNumber()-1, pageable.getPageSize());
        }
        pageModel = new PageImpl<>(resultList, pageable, pagedListMap.getTotalElements());
        return pageModel;
    }

    /**
     * (基于当前注入泛型)根据Id获取一条数据
     * @author: wei.fu
     * @param id
     * @return T
     */
    public T jpaGetSingleEntityById(Serializable id){
        Serializable serId = this.convertIdType(this.getCurrentTClass(), id);
        return em.find(this.getCurrentTClass(), serId);
    }


    /**
     * (动态传入泛型)根据Id获取一条数据
     * @author: wei.fu
     * @param id
     * @return R
     */
    public <R> R jpaGetSingleEntityById(Class<R> tClass, Serializable id){
        try{
            Serializable serId = this.convertIdType(tClass, id);
            return em.find(tClass, serId);
        }catch (Exception e){
            log.error("BaseService.jpaGetSingleEntityById 异常:" + e.getMessage(), e);
            return null;
        }finally {
            em.close();
        }
    }


    /*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑(Select查询部分)基于EntityManager的CreateNativeQuery↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/


    /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓(增删改)基于EntityManager的增删改↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/


    /**
     * (基于当前注入泛型)保存方法
     * @author: wei.fu
     * @param entity
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean jpaSave(T entity){
        return this.jpaSave(this.getCurrentTClass(), entity);
    }

    /**
     * (基于当前注入泛型)保存并Flush方法
     * @author: wei.fu
     * @param entity
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean jpaSaveAndFlush(T entity){
        return this.jpaSave(this.getCurrentTClass(), entity, true);
    }

    /**
     * (动态传入泛型)保存方法
     * @author: wei.fu
     * @param entity
     * @param isAutoFlush
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public <R> Boolean jpaSave(Class<R> tClass, R entity, boolean... isAutoFlush){
        boolean isFlush = isAutoFlush.length > 0 && isAutoFlush[0];
        try{
            em.persist(entity);
            return true;
        }catch (Exception e){
            log.error("BaseService.jpaSave 异常:" + e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }finally {
            if(isFlush){
                em.flush();
            }
            em.close();
        }
    }

    /**
     * (动态传入泛型)保存并刷新方法
     * @author: wei.fu
     * @param tClass
     * @param entity
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public <R> Boolean jpaSaveAndFlush(Class<R> tClass, R entity){
        return this.jpaSave(tClass, entity, true);
    }

    /**
     * (基于当前注入泛型)批量更新操作
     * @author: wei.fu
     * @param listEntities
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean jpaSaveBatch(Collection<T> listEntities){
        return this.jpaSaveBatch(this.getCurrentTClass(), listEntities);
    }

    /**
     * (动态传入泛型)批量创建操作
     * @author: wei.fu
     * @param listEntities
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public <R> Boolean jpaSaveBatch(Class<R> tClass, Collection<R> listEntities){
        try{
            List<R> listEntity = Convert.toList(tClass, listEntities);
            for (int i = 0; i < listEntity.size(); i++) {
                em.persist(listEntity.get(i));
                if (i % 1000 == 0) {
                    em.flush();
                }
            }
            em.flush();
            return true;
        }catch (Exception e){
            log.error("BaseService.jpaSaveBatch 异常:" + e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }finally {
            em.close();
        }
    }

    /**
     * (基于当前注入泛型)根据Id更新方法
     * @author: wei.fu
     * @param id
     * @param entity
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean jpaUpdateById(Serializable id, T entity){
        return this.jpaUpdateById(this.getCurrentTClass(), id, entity);
    }


    /**
     * (动态传入泛型)根据Id更新方法
     * @author: wei.fu
     * @param tClass
     * @param id
     * @param entity
     * @param <R>
     * @param isAutoFlush
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public <R> Boolean jpaUpdateById(Class<R> tClass, Serializable id, R entity, boolean... isAutoFlush){
        boolean isFlush = isAutoFlush.length > 0 && isAutoFlush[0];
        try{
            R dbEntity = this.jpaGetSingleEntityById(tClass, id);
            /**
             * 属性拷贝,忽略传入的null值转换
             */
            CopyOptions copyOptions = new CopyOptions();
            copyOptions.setIgnoreNullValue(true);
            copyOptions.setIgnoreError(true);
            copyOptions.setIgnoreCase(false);
            BeanUtil.copyProperties(entity, dbEntity, copyOptions);
            /**
             * Id重新赋传入的值
             */
            ReflectUtil.setFieldValue(dbEntity, this.getIdFieldName(tClass), id);
            em.merge(dbEntity);
            BeanUtil.copyProperties(dbEntity, entity, true);
            return true;
        }catch (Exception e){
            log.error("BaseService.jpaUpdateById 异常:" + e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }finally {
            if(isFlush){
                em.flush();
            }
            em.close();
        }
    }

    /**
     * (基于当前注入泛型)根据Id更新并Flush方法
     * @author: wei.fu
     * @param id
     * @param entity
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean jpaUpdateByIdAndFlush(Serializable id, T entity){
        return this.jpaUpdateById(this.getCurrentTClass(), id, entity, true);
    }

    /**
     * (动态传入泛型)根据Id更新方法并Flush
     * @author: wei.fu
     * @param tClass
     * @param id
     * @param entity
     * @param <R>
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public <R> Boolean jpaUpdateByIdAndFlush(Class<R> tClass, Serializable id, R entity){
        return this.jpaUpdateById(tClass, id, entity, true);
    }


    /**
     * (基于当前注入泛型)批量更新操作
     * @author: wei.fu
     * @param listEntities
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean jpaUpdateBatch(Collection<T> listEntities){
       try{
           List<Boolean> retList = new ArrayList<>();
           for (T r: listEntities) {
               Serializable fieldValue = (Serializable)ReflectUtil.getFieldValue(r, this.getIdFieldName(this.getCurrentTClass()));
               retList.add(this.jpaUpdateById(this.getCurrentTClass(), fieldValue, r, false));
           }
           return Linq.asEnumerable(retList).any(c -> !c);
       }catch (Exception e){
           log.error("BaseService.jpaUpdateBatch 异常:" + e.getMessage(), e);
           TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
           return false;
       }finally {
           em.flush();
           em.close();
       }
    }


    /**
     * (基于当前注入泛型)根据Id删除一条方法
     * @author: wei.fu
     * @param id
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean jpaDeleteById(Serializable id){
        return this.jpaDeleteById(this.getCurrentTClass(), id);
    }

    /**
     *(基于当前注入泛型)根据IdList删除多条数据
     * @author: wei.fu
     * @param idList
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean jpaDeleteByIds(Collection<? extends Serializable> idList){
        return this.jpaDeleteByIds(this.getCurrentTClass(), idList);
    }

    /**
     * (动态传入泛型)根据Id删除一条方法
     * @author: wei.fu
     * @param id
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public <R> boolean jpaDeleteById(Class<R> tClass, Serializable id){
        try{
            R dbEntity = this.jpaGetSingleEntityById(tClass, id);
            em.remove(dbEntity);
            return true;
        }catch (Exception e){
            log.error("BaseService.jpaDeleteById 异常:" + e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }finally {
            em.flush();
            em.close();
        }
    }

    /**
     * (动态传入泛型)根据IdList删除多条数据
     * @author: wei.fu
     * @param idList
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public <R> boolean jpaDeleteByIds(Class<R> tClass, Collection<? extends Serializable> idList){
        try{
            for (Serializable id: idList) {
                R dbEntity = this.jpaGetSingleEntityById(tClass, id);
                em.remove(dbEntity);
            }
            return true;
        }catch (Exception e){
            log.error("BaseService.jpaDeleteByIds 异常:" + e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }finally {
            em.flush();
            em.close();
        }
    }

    /**
     * (基于当前注入泛型)根据实体Id判断是创建还是修改
     * @author: wei.fu
     * @param entity
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean jpaSaveOrUpdate(T entity){
        return this.jpaSaveOrUpdate(this.getCurrentTClass(), entity);
    }

    /**
     * (基于当前注入泛型)根据实体Id判断是创建还是修改并Flush
     * @author: wei.fu
     * @param entity
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean jpaSaveOrUpdateAndFlush(T entity){
        return this.jpaSaveOrUpdate(this.getCurrentTClass(), entity, true);
    }

    /**
     * (动态传入泛型)根据实体Id判断是创建还是修改 并且Flush
     * @author: wei.fu
     * @param entity
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public <R> Boolean jpaSaveOrUpdateAndFlush(Class<R> tClass, R entity){
        return this.jpaSaveOrUpdate(tClass, entity, true);
    }

    /**
     * (动态传入泛型)根据实体Id判断是创建还是修改
     * @author: wei.fu
     * @param entity
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public <R> Boolean jpaSaveOrUpdate(Class<R> tClass, R entity, boolean... isAutoFlush){
        Boolean retStatus = false;
        String idFieldName = this.getIdFieldName(tClass);
        Object fieldValue = ReflectUtil.getFieldValue(entity, idFieldName);
        if(Validator.isEmpty(fieldValue)){
            retStatus = this.jpaSave(tClass, entity, isAutoFlush);
        }else{
            retStatus = this.jpaUpdateById(tClass, this.convertIdType(tClass, fieldValue), entity, isAutoFlush);
        }
        return retStatus;
    }

    /**
     * (动态传入泛型)批量更新操作
     * @author: wei.fu
     * @param listEntities
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    public <R> Boolean jpaUpdateBatch(Class<R> tClass, Collection<R> listEntities){
        List<Boolean> retList = new ArrayList<>();
        for (R r: listEntities) {
            Serializable fieldValue = (Serializable)ReflectUtil.getFieldValue(r, this.getIdFieldName(tClass));
            retList.add(this.jpaUpdateById(tClass, fieldValue, r));
        }
        return Linq.asEnumerable(retList).any(c -> !c);
    }


    /*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑(增删改)基于EntityManager的增删改↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/



    /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓(通用部分)基于EntityManager↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/

    /**
     * 根据Sql获取数据Count数
     * @author: wei.fu
     * @param sqlOrSqlId
     * @return Long
     */
    public Long jpaGetCount(String sqlOrSqlId){
        return this.jpaGetCount(sqlOrSqlId, null);
    }

    /**
     * 根据Sql和参数获取数据Count数
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @return long
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Long jpaGetCount(String sqlOrSqlId, Map<String, Object> params){
        Long totalCount = 0L;
        try{
            if(this.isTemplateSql(sqlOrSqlId)){
                sqlOrSqlId = SqlWrapper.renderTemplate(sqlOrSqlId, params);
            }
            sqlOrSqlId = "SELECT COUNT(0) COUNT_NUM FROM (" + sqlOrSqlId + ") AS TOTAL";
            Query queryCount = this.buildQuery(sqlOrSqlId, params, null, false);
            Object singleResult = queryCount.getSingleResult();
            if(Validator.isNull(singleResult)){
                return totalCount;
            }
            return Convert.toLong(singleResult,0L);
        }catch (Exception e){
            log.error("BaseService.jpaGetCount 异常:" + e.getMessage(), e);
            return totalCount;
        }finally {
            em.close();
        }
    }


    /**
     * 查询全部数据(返回值类型为 List<Map<String, Object>>)
     * @author: wei.fu
     * @return List<Map<String, Object>>
     */
    public List<Map<String, Object>> getAllListMap(){
        String selAllSql = SqlWrapper.create(this.getCurrentTClass()).build();
        return this.jpaGetListMap(selAllSql);
    }

    /**
     * 查询全部数据(返回值类型为 List<Map<String, Object>>)
     * @author: wei.fu
     * @param tClass
     * @return List<Map<String, Object>>
     */
    public <R> List<Map<String, Object>> jpaGetAllListMap(Class<R> tClass){
        String selAllSql = SqlWrapper.create(tClass).build();
        return this.jpaGetListMap(selAllSql);
    }

    /**
     * 查询全部数据(返回值类型为 List<T>)
     * @author: wei.fu
     * @return List<T>
     */
    public List<T> jpaGetAllListEntity(){
        String selAllSql = SqlWrapper.create(this.getCurrentTClass()).build();
        return this.jpaGetListEntity(selAllSql);
    }

    /**
     * 查询全部数据(返回值类型为 List<R>)
     * @author: wei.fu
     * @param tClass
     * @return List<R>
     */
    public <R> List<R> jpaGetAllListEntity(Class<R> tClass){
        String selAllSql = SqlWrapper.create(tClass).build();
        return this.jpaGetListEntity(tClass, selAllSql);
    }


    /**
     * 根据Sql查询某一列集合(返回值类型为 List<R>)
     * @author: wei.fu
     * @param typeClass (取决于数据库中列字段的类型,可选参数例如:Long.class, Integer.class, Date.class, Double.class ......)
     * @param sqlOrSqlId
     * @return List<R>
     */
    public <R> List<R> jpaGetSingleColumnList(Class<R> typeClass, String sqlOrSqlId){
        return this.jpaGetSingleColumnList(typeClass, sqlOrSqlId, null);
    }


    /**
     * 根据Sql查询某一列集合(返回值类型为 List<R>)
     * @author: wei.fu
     * @param typeClass (取决于数据库中列字段的类型,可选参数例如:Long.class, Integer.class, Date.class, Double.class ......)
     * @param sqlOrSqlId
     * @param params
     * @return List<R>
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public <R> List<R> jpaGetSingleColumnList(Class<R> typeClass, String sqlOrSqlId, Map<String, Object> params){
        List<R> resList = new ArrayList<>();
        try {
            String[] conditions = new String[]{",", "*"};
            if(!this.validatorSqlSpec(sqlOrSqlId, conditions)){
                throw new Exception("Sql: '"+ sqlOrSqlId +"' 传入的Sql语句包含多列,请检查Sql重新调用此方法");
            }
            IEnumerable<Map<String, Object>> linqListMap = Linq.asEnumerable(this.jpaGetListMap(sqlOrSqlId, params));
            /**
             * 判断Map中至少有一个元素的才会执行if里
             */
            if(linqListMap.any(c -> c.size() <= 1)){
                /**
                 * where过滤Map不为空并且第一个元素的value有值得才取出
                 */
                resList = linqListMap.where(m -> Validator.isNotEmpty(Linq.asEnumerable(m.entrySet()).first().getValue())
                        && MapUtil.isNotEmpty(m)).select(a -> {
                    return Convert.convert(typeClass, Linq.asEnumerable(a.entrySet()).first().getValue());
                }).toList();
            }
            return resList;
        }catch (Exception e){
            log.error("BaseService.jpaGetSingleColumnList 异常:" + e.getMessage(), e);
            return resList;
        }finally {
            em.close();
        }
    }


    /*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑(通用部分)基于EntityManager↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/



    /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓(工具类部分)基于EntityManager↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/

    /**
     * 根据tClass转换对应的Id类型
     * @author: wei.fu
     * @param tClass
     * @param id
     * @param <R>
     * @return Serializable
     */
    private <R> Serializable convertIdType(Class<R> tClass, Object id){
        Serializable retId = DEFAULT_ID_ERROR_VALUE;
        String longType = "java.lang.Long";
        String intType = "java.lang.Integer";
        String strType = "java.lang.String";
        IEnumerable<Field> fields = Linq.asEnumerable(ReflectUtil.getFields(tClass));
        Field field = fields.firstOrDefault(c -> c.isAnnotationPresent(Id.class));
        String fieldType = field == null ? longType : field.getType().getName();

        if(longType.equalsIgnoreCase(fieldType)){
            retId = Convert.toLong(id, DEFAULT_ID_ERROR_VALUE);
        }else if(intType.equalsIgnoreCase(fieldType)){
            retId = Convert.toInt(id, -1);
        }else if(strType.equalsIgnoreCase(fieldType)){
            retId = Convert.toStr(id, "-1");
        }
        return retId;
    }

    /**
     * 合并丢失的字段,有一些字段在查询Map的时候自动转换为小驼峰,但是实体还是下划线分割这种的
     * @author: wei.fu
     * @param resultEntity
     * @param resultMap
     */
    private <R> void mergeLostFields(R resultEntity, Map<String, Object> resultMap){
        if(Validator.isNotNull(resultEntity) && Validator.isNotNull(resultMap)){
            /**
             * 获取所有字段看是否有属性包含 "_"
             */
            IEnumerable<Field> fields = Linq.asEnumerable(ReflectUtil.getFields(resultEntity.getClass()));
            if(fields.any(a -> a.getName().contains(FIELD_UNDERSCORE_NAME))){
                List<Field> supFields = fields.where(a -> a.getName().contains(FIELD_UNDERSCORE_NAME)).toList();
                supFields.forEach(f -> {
                    String fieldKey = UnderlineToCamelUtil.underlineToCamel(f.getName());
                    ReflectUtil.setFieldValue(resultEntity, f.getName(), resultMap.get(fieldKey));
                });
            }
        }
    }


    /**
     * 合并丢失的字段,有一些字段在查询Map的时候自动转换为小驼峰,但是实体还是下划线分割这种的
     * @author: wei.fu
     * @param resultList
     * @param resultListMap
     */
    private <R> void mergeLostFields(List<R> resultList, List<Map<String, Object>> resultListMap) {
        if(resultList.size() == resultListMap.size()){
            IEnumerable<R> linqList = Linq.asEnumerable(resultList);
            if(linqList.any() && Validator.isNotNull(linqList.first())){
                R firstEntity = linqList.first();
                IEnumerable<Field> fields = Linq.asEnumerable(ReflectUtil.getFields(firstEntity.getClass()));
                if(fields.any(a -> a.getName().contains(FIELD_UNDERSCORE_NAME))){
                    List<Field> supFields = fields.where(a -> a.getName().contains(FIELD_UNDERSCORE_NAME)).toList();
                    /**
                     * 遍历转换后的结果集
                     */
                    for (int i = 0; i < resultList.size(); i++) {
                        R tEntity = resultList.get(i);
                        Map<String, Object> rMap = resultListMap.get(i);
                        supFields.forEach(f -> {
                            String fieldKey = UnderlineToCamelUtil.underlineToCamel(f.getName());
                            ReflectUtil.setFieldValue(tEntity, f.getName(), rMap.get(fieldKey));
                        });
                    }
                }
            }
        }
    }


    /**
     * 判断Sql是否合法
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param condition
     * @return
     */
    private Boolean validatorSqlSpec(String sqlOrSqlId, String... condition) {
        int startPos = StrUtil.indexOfIgnoreCase(sqlOrSqlId, "select");
        int endPos = StrUtil.indexOfIgnoreCase(sqlOrSqlId, "from");
        String selectSql = StrUtil.sub(sqlOrSqlId, startPos, endPos);
        if(Validator.isNull(condition) || startPos <= 0 || endPos <= 0){
            return true;
        }
        /**
         * 判断字符串中是否包含传递过来的condition
         */
        IEnumerable<String> retList = Linq.asEnumerable(condition).where(c -> StrUtil.containsIgnoreCase(selectSql, c));
        return !retList.any();
    }




    /**
     * 获取当前泛型的Class
     * @author: wei.fu
     * @return Class<T>
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private Class<T> getCurrentTClass(){
        Class <T> entityClass = null;
        try{
           entityClass = (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }catch (Exception e){
            log.error("BaseService.getCurrentTClass 异常:" + e.getMessage(), e);
        }
        return entityClass;
    }

    /**
     * 公用的 - 构建Query对象
     * @author: wei.fu
     * @param sqlOrSqlId
     * @return Query
     */
    public Query buildQuery(String sqlOrSqlId){
        return this.buildQuery(sqlOrSqlId, null, null, true);
    }

    /**
     * 公用的 - 构建Query对象
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @return Query
     */
    public Query buildQuery(String sqlOrSqlId, Map<String, Object> params){
        return this.buildQuery(sqlOrSqlId, params, null, true);
    }

    /**
     * 公用的 - 构建Query对象
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @param pageable
     * @return Query
     */
    public Query buildQuery(String sqlOrSqlId, Map<String, Object> params, Pageable pageable){
        return this.buildQuery(sqlOrSqlId, params, pageable, true);
    }

    /**
     * 公用的 - 构建Query对象
     * @author: wei.fu
     * @param sqlOrSqlId
     * @param params
     * @param pageable
     * @param isRetMap (是否返回Map)
     * @return Query
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Query buildQuery(String sqlOrSqlId, Map<String, Object> params, Pageable pageable, Boolean isRetMap){
        if(this.isTemplateSql(sqlOrSqlId)){
            sqlOrSqlId = SqlWrapper.renderTemplate(sqlOrSqlId, params);
        }
        Query query = em.createNativeQuery(sqlOrSqlId);

        if(params != null){
            for(String key : params.keySet()){
                if(StrUtil.containsIgnoreCase(sqlOrSqlId, StrUtil.format(":{}", key))){
                    query.setParameter(key, params.get(key));
                }
            }
        }
        if (null != pageable && pageable.getPageNumber() >= 0 && pageable.getPageSize() != 0) {
            /**
             * 起始对象位置
             */
            query.setFirstResult(pageable.getPageSize() * (pageable.getPageNumber() - 1));
            /**
             * 查询对象个数
             */
            query.setMaxResults(pageable.getPageSize());
        }
        if(isRetMap){
            /**
             * 转换小驼峰返回
             */
            query.unwrap(NativeQueryImpl.class).setResultTransformer(new HashMapResultTransformer(HashMap.class));
        }
       return query;
    }


    /**
     * 根据clazz获取主键字段Name
     * @author: wei.fu
     * @param clazz
     * @param <R>
     * @return String
     */
    private <R> String getIdFieldName(Class<R> clazz){
        try{
            String fieldName = Linq.asEnumerable(ReflectUtil.getFields(clazz)).where(c ->
                    c.isAnnotationPresent(AssignID.class)
                    || c.isAnnotationPresent(SeqID.class)
                    || c.isAnnotationPresent(Id.class)
                    ||c.isAnnotationPresent(AutoID.class)).select(a -> a.getName()).distinct().firstOrDefault();
            return StrUtil.isNotEmpty(fieldName) ? fieldName : DEFAULT_ID_NAME;
        }catch (Exception e){
            log.error("BeetlSqlBaseService.internalGetIdFieldName 异常:" + e.getMessage(), e);
            return DEFAULT_ID_NAME;
        }
    }


    /**
     * 根据传入的SqlId参数自动判断是sql还是SqlId
     * @param sqlOrSqlId
     * @return String
     */
    private Boolean isTemplateSql(String sqlOrSqlId){
        String absolutePath = SqlTemplate.classPathResource.getAbsolutePath();
        String removeAllLineBreakStr = StrUtil.removeAllLineBreaks(sqlOrSqlId);
        List<String> splitStrList = Linq.asEnumerable(StrUtil.split(removeAllLineBreakStr.replace("\t", ""), ".")).toList();

        if(splitStrList.size() > 0) {
            splitStrList.remove(splitStrList.size() - 1);
        }
        if(splitStrList.size() >= 1 && splitStrList.size() <= 6){
            String joinPath = CollUtil.join(splitStrList, "/");
            /**
             * 判断Sql文件是否存在
             */
            if(FileUtil.exist(StrUtil.format("{}/{}.md", absolutePath, joinPath)) || FileUtil.exist(StrUtil.format("{}/{}.sql", absolutePath, joinPath))){
                return true;
            }
        }
        return false;
    }

    /*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑(工具类部分)基于EntityManager↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/

}

::: tip
以上只是简单的Demo,具体实践中一定要活学活用,还有更多好玩的用法等着你来探索
:::

基于Java的泛型和反射实现通用的增删改查(2)——通用增删改查操作的底层设计 一、设计理念  在互联网项目或者其他传统Web项目的开发过程中,对数据库的操作可以说是项目的核心和根本,而数据库操作无非就是增删改查,而对所有表的增删改查操作都大同小异,非常相似。如果我们能够将对单表的增删改查操作抽象出来放在父类中去实现,让所有的子类继承这个已实现了增删改查操作的父类,那么我们的工作效率无疑会大大地提升,也会使我们从这些简单无聊但又不得不去做的工作中解脱出来,将有限的精力投入到较... 阅读详情

相关推荐

基于Java的Service层单体操作抽象设计与实践

在企业级应用开发中,服务接口不仅是系统内部各模块之间协作的契约,更是对外暴露能力、实现松耦合架构的核心载体。一个清晰、稳定且具备扩展性的服务接口设计,能够显著提升系统的可维护性、可测试性和团队协作效率。尤其在微服务或分布式架构背景下,服务接口承担着跨进程通信、协议转换和数据封装的关键职责。因此,如何科学地定义服务接口并建立统一的设计规范,成为构建高质量软件系统的重要前提。服务接口的本质是“契约”——它规定了调用方可以期待的行为、输入输出格式以及可能发生的异常情况。

weixin_36303305的博客 978

利用泛型封装通用的service层

身为一名开发人员,大家都知道,我们经常会在项目中大量的编写许多重复的代码,比如说public Entity find(String id);像这种代码,简单,但是写多了,可能也会容易出错,那么我们能不能直接编写一套完整的,通用的方法呢,这样既不用重复编写,还不用出错,说道通用的方法,泛型是个不错的选择.基础架构:spring-boot+spring mvc+spring jpa.jpa是个好东西,...

瓦力-眼观世界 1万+

TMS320C6678开发笔记1-6---C6678单核烧写程序

第6节 单核烧写加载程序 6.1节 TI参考文档 参考文档:《KeystoneI Bootloader Resources and FAQ》讲的非常好,建议一定要看 https://processors.wiki.ti.com/index.php/KeystoneI_Bootloader_Resources_and_FAQ#Direct_Boot_Examples_.28without_IBL.29 里面有三个工程: C6678 EVM SPI boot example C6657 EVM ..

kunkliu的博客 5712

BaseService和其实现类

BaseService和其实现类 开发工具与关键技术:Eclipse、java 作者:梁添荣 撰写时间:2020-05-08 在service层,我们经常会写基本的增删查改方法,但有很多模块都有类似的写法,所以,抽取常用的增删查改BaseService接口,再实现该接口为BaseServiceImpl,通过service层的实现类继承BaseServiceImpl,就有了各个增删查改的方法了,只...

weixin_44619313的博客 5001

python使用TensorRT报错,多线程或多进程中使用问题

python使用TensorRT报错,Cuda Runtime问题

qq_44224801的博客 756

Bochs源码分析 - 4: 使用ida来调试bochs

前言 bochs内部提供了一个调试器,但是这个命令行调试器相当难用,想找一个gui的debugger。第一次是在百度百科的bochs词条中介绍的peter-bochs-debugger调试器(java编写),但是后来发现ida也有一个bochs调试器,因为对ida比较熟悉,就选用此作为bochs调试器。 在配置过程中参考博客 https://blog.csdn.net/cssxn/article/details/90738498 中的配置,但是这是直接发布版本,拿源码编译...

WriteAnything_的博客 2766

开发过程中的总结 BaseService 为所有的 Controller或Service 提供一个公共获取 Service 的文件,减少重复注入

这种方式看起来更好一些,将不同的服务类直接通过staticfinal的方式在类内静态声明(需要先从applicationContext中获取),当其成为一个静态属性时,其他的controller或者service直接通过类名。其他Controller或者Service中如下方式继承,则可以省去重复注入,为了减少Controller中的注入,甚至可以直接在不同的Service继承,controller可以完全不使用。这是一种好的方式但是还是存在部分浪费的嫌疑。...

weixin_44131922的博客 2579

SAP农产品增值税进项税解决方案

(三)购进农产品用于生产经营且不构成货物实体的(包括包装物、辅助材料、燃料、低值易耗品等),用于生产适用13%税率货物的扣除率为10%,用于生产适用9%税率货物的扣除率为9%。具体计算公式为: 当期允许抵扣农产品增值税进项税额=当期耗用农产品数量×农产品平均购买单价×扣除率/(1+9%)

weixin_44228539的博客 1203

Spring Data JPA之Service编码规范

乾道核心等系统后台开发Service编码规范 1、编码说明 1)架设计之初,优先考虑降低开发成本;于是,去掉了实体类接口dao的实现类;所以,sql语句的拼写调整至service层。 2)service层中的方法,凡是调用dao层带有@Modifying注解的方法,必须加@Transactional,且增加属性rollbackFor=Exception.class 即 @Transacti...

春风化雨 4878

ICC2: pin shape不在track上引起的drc如何解决?

我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?

m0_61544122的博客 454

AMBA-CHI协议详解(一)

CHI体系结构是一种可扩展、一致性的集线器接口和片上互联,可由多个组件使用。CHI体系结构允许根据性能、功耗和面积系统要求灵活地进行组件连接拓扑。硬件一致性使系统组件能够共享内存,而无需维护软件缓存以保持一致性。如果两个组件对同一存储器位置的写入可被所有组件以相同的顺序观察到,则存储器区域是一致的。

Crazzy_M的博客 1万+

<项目经验> 基于jpa封装BaseDao,BaseService

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33979363的博客 2570

YOLOv11改进策略【Backbone/主干网络】|替换HGNetV2骨干,包含RT-DETR中的l、x模型

本文记录的是基于HGNetv2的YOLOv11目标检测改进方法研究。本文利用HGNetv2替换YOLOv11的骨干网络,HGNetv2 通过其 GPU 推理友好的 3×3 标准卷积和层次化 HG Block 结构,能够为骨干网络提供高效且完整的特征提取能力。并且其中的和可在降低计算量的同时丰富特征表达,增强对多尺度目标特征的捕获能力,进而提高模型精度。本文配置了原论文中rtdetr-lrtdetr-x,以满足不同算力和检测精度的需求。

Limiiiing的博客 680

Spring Data JPA 封装API

import java.util.List; import java.util.Map; import java.util.Optional; public interface BaseService<T, ID> { /** * 分页查询 * * @param pageNum 当前页 * @param pageSize 每...

吕小小布的博客 2271

SpringBoot4.0+JDK25+GraalVM实战:云原生新纪元,微服务性能翻倍的落地指南

三者的组合不是偶然,而是“框架优化+JDK升级+虚拟机革新”的必然结果——SpringBoot4.0完善了对GraalVM原生镜像的支持,JDK25强化了云原生与AOT编译能力,GraalVM则提供了极致的启动速度和资源利用率,三者协同,刚好命中云原生微服务的核心痛点。SpringBoot4.0+JDK25+GraalVM的组合,不是简单的版本升级,而是云原生微服务的一次性能革命。

2601_94871597的博客 1154

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

封装Service层公用CRUD操作,提高开发效率

项目架构: 项目采取前后分离开发模式,前端:antd pro 2.0,后端:spring cloud + spring boot + JPA。数据交换:json 最近在项目组开发中使用到JPA,初次使用JPA感觉很强大,解放了repository层的实现,提高了开发效率。 在git上评审项目组成员代码时,发现各应用模块在Service层都对其下业务创建了CRUD操作,查看完项目代码,感觉80%...

bin_zi_123的专栏 3088

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

MyBatis-Plus 通用查询工具类

mybatis-plus简称MP是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。 这是官方给的定义,关于mybatis-plus的更多介绍及特性,可以参考mybatis-plus官网 。那么它是怎么增强的呢?其实就是它已经封装好了一些crud方法,我们不需要再写xml了,直接调用这些方法就行,就类似于JPA。 下面是在MP为基础封装了一个查询类,实现了如果需要增加查询条件只需在前端修改即可。 查询工具 SearchModel public .

li5672的专栏 3485

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

Spring boot jpa 底层封装

pom: <!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api --> <dependency> <groupId>javax.persistence</groupId> <artifactId>ja...

akuq88038的博客 484

基于spring data jpa封装带有动态分页查询、动态条件求和的基础service类和基础controller类

基于spring data jpa封装带有动态分页查询、动态条件求和的基础service类和基础controller类 本文章介绍的是封装一个带有动态条件分页查询和动态条件求和基类 项目:springBoot项目 前提条件:引入spring data jpa依赖 源码地址:https://github.com/lizhongxiang12138/eurekaManage 代码结构 │ .giti...

github_35976996的博客 3029

springboot极简教程007-工程建议

组织结构 实体类 建议把实体类统一放在某个包下,包名建议取名: model(模型,也就是MCV模式中的M,Django也是取的该值) entity(Java有些封装的函数参数就是用的这个,也比较推荐) bean(java中的bean就是模型层的类,意即model) pojo(Plain Ordinary Java Object的缩写;不含业务逻辑的java简单对象;完全POJO的系统也称为轻量级...

大星星的专栏 294

dao加service加mysql实例_Java程序员懒人必备神技,不写一句Dao层和Service层代码实现对数据库的增删改查...

HI,大家好,今天给大家分享一个懒人必备神技,不写一句 Service层和dao(数据库操作层)的代码而实现增删改查。不写一句Service层和dao(数据库操作层)的代码而实现增删改查?看到这里,你可能会说:老铁,不写重复的代码我知道,把重复的代码提取出来封装成类。这个我早就知道了,至于不写Service和dao的代码能直接操作数据库,难道直接写在Controllor层么?别开玩笑了。别急,我说...

weixin_29563497的博客 458

SSM(三)公共Common模块的抽离(2)

SSM(三)公共Common模块的抽离(2) 前言 在 SSM(三)公共Common模块的抽离(1) 文章中,对COMMON模块已经作了简单配置,下面将介绍如何抽取基础的增删改查模块,以便在各个WEB中复用。 新建W3CJAVA-WEB-COMMON模块 参照前面的文章开始部分新建W3CJAVA-WEB-COMMON模块,可以看到如下图的项目目录结构: 之所以又单独新建一个W...

HeartMa′Blog 909

S-mall-ssm 通用Mapper原理深度解析:注解+反射+泛型+静态代理如何实现ORM?

很多同学学完 SSM(Spring + SpringMVC + MyBatis)后,最头疼的就是"关联查询":查一个分类要手动再查商品、查一个订单要手动拼商品明细,代码越写越长,逻辑越堆越乱。而 **S-mall-ssm 通用Mapper** 给出了一个非常聪明的答案:用 **注解 + 反射 + 泛型 + 静态代理** 四种技术组合,实现了一套轻量级的 ORM 自动关联查询机制。这个仿天猫的 **

gitblog_01182的博客 906

Spring Boot核心原理与实战开发指南

Spring Boot作为Java生态中的主流框架,通过约定优于配置原则大幅简化了Spring应用的开发流程。其核心机制自动配置基于条件注解实现,能够智能检测并加载所需组件。框架采用内嵌容器设计,使应用打包为独立可执行JAR,完美适配云原生和微服务架构。在开发实践中,结合MyBatis-Plus或JPA等持久层框架,可快速构建企业级应用。通过Docker容器化和K8s部署,能实现高效的CI/CD流程。Spring Boot 3.x版本更支持GraalVM原生镜像和虚拟线程等前沿特性,为高性能应用开发提供新可

WGH100817的博客 509

SpringBoot+Vue3+DeepSeek构建智能健身管理系统实战

在Web开发领域,前后端分离架构已成为现代应用开发的主流范式,它通过解耦前端展示与后端业务逻辑,实现了开发效率与维护性的双重提升。其核心原理在于前端通过HTTP协议调用后端提供的RESTful API接口进行数据交互,这种模式让技术团队能够并行开发、独立部署。从技术价值看,前后端分离不仅提升了开发体验,更通过清晰的职责划分增强了系统的可扩展性。在实际应用场景中,健身管理系统这类业务边界清晰的项目,成为学习前后端分离技术的理想载体。通过整合SpringBoot后端框架与Vue3前端框架,开发者能够完整实践从数

weixin_34342207的博客 358

每周小记——SpringBoot&Mybatis-Plus

本文概述SpringBoot实践及整合MyBatis-Plus与Swagger,涵盖基础配置(环境搭建、YAML、多环境部署、热部署),框架整合(Swagger3自动API文档、MyBatis-Plus简化CRUD/逻辑删除/乐观锁/代码生成器/多数据源),高级特性(YAML封装、函数式接口、ActiveRecord模式),实用技巧(自定义Banner、分页/自定义SQL、枚举处理、Service封装),以代码示例驱动企业级开发。

weixin_57655687的博客 2406
上一篇: Uninstall Tool v3.5.9.5654 单文件版
下一篇: Sql构造器 (SqlWrapper)
普通网友
博客等级 码龄14年 19粉丝 3原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值