首页 > 数据库 >hibernate 自定义表名与列名 - 增删改查分页 - 兼容Mysql和Oracle

hibernate 自定义表名与列名 - 增删改查分页 - 兼容Mysql和Oracle

时间:2024-09-27 08:54:36浏览次数:10  
标签:hibernate String 自定义 StringBuilder Mysql sql import data append

1. 新增service,先组装SQL

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class DataService {

    @Autowired
    private CustomRepository customRepository;

    @Autowired
    private EventService EventService;

    @Value("${spring.jpa.database}")
    private String database;

    public ApiResult addCustomData(CustomDataDTO customDataDTO) {
        String cusTableName = customDataDTO.getTargetTable();
        List<CustomColumnData> dataList = customDataDTO.getDatas();
        StringBuilder sql = new StringBuilder();
        StringBuilder strColumns = new StringBuilder();
        StringBuilder strValues = new StringBuilder();
        for (int i =0; i < dataList.size(); i++) {
            CustomColumnData data = dataList.get(i);
            strColumns.append("`").append(data.getColumnName()).append("`")
                    .append((i<dataList.size() - 1) ? "," : "");
            strValues.append("'").append(data.getColumnValue()).append("'")
                    .append((i<dataList.size() - 1) ? "," : "");
        }
        sql.append(" insert into ").append(cusTableName).append(" (").append(strColumns).append(") values ").append("(").append(strValues).append(")");
        int res = customRepository.insertData(sql.toString());
        return ApiResult.ok(res);
    }

    public ApiResult addCustomDataAutoID(CustomDataDTO customDataDTO) {
        String cusTableName = customDataDTO.getTargetTable();
        List<CustomColumnData> dataList = customDataDTO.getDatas();
        StringBuilder strColumns = new StringBuilder();
        StringBuilder strValues = new StringBuilder();
        for (int i =0; i < dataList.size(); i++) {
            CustomColumnData data = dataList.get(i);
            strColumns.append(data.getColumnName())
                    .append((i<dataList.size() - 1) ? "," : "");
            strValues.append("'").append(data.getColumnValue()).append("'")
                    .append((i<dataList.size() - 1) ? "," : "");
        }

        int res = customRepository.insertDataAutoID(cusTableName, strColumns.toString(), strValues.toString());
        return ApiResult.ok(res);
    }

    public ApiResult updateCustomData(CustomDataDTO customDataDTO) {
        String cusTableName = customDataDTO.getTargetTable();
        List<CustomColumnData> dataList = customDataDTO.getDatas();
        StringBuilder setValues = new StringBuilder();
        for (int i =0; i < dataList.size(); i++) {
            CustomColumnData data = dataList.get(i);
            if (data.getColumnName() != null && !data.getColumnName().isEmpty()) {
                setValues.append(data.getColumnName())
                        .append("=").append("'").append(data.getColumnValue()).append("'")
                        .append((i<dataList.size() - 1) ? "," : "");
            }
        }

        int res = customRepository.updateDataSetByID(cusTableName , String.valueOf(setValues), customDataDTO.getDataId());
        return ApiResult.ok(res);
    }

    public ApiResult deleteCustomDataByID(CustomDataCondition customDataCondition) {
        String cusTableName = customDataDTO.getTargetTable();
        StringBuilder setValues = new StringBuilder();
        List<Long> longList = customDataCondition.getIdList();
        for (int i =0; i < longList.size(); i++) {
            long id = longList.get(i);
            if (id > 0) {
                setValues.append(id)
                        .append((i<longList.size() - 1) ? "," : "");
            }
        }
        int res = customRepository.deleteDataSetByID(cusTableName, setValues.toString());
        return ApiResult.ok(res);
    }


    public ApiResult getAll(CustomDataQueryDTO customDataDTO) {
        String cusTableName = customDataDTO.getTargetTable();
        List<CustomColumnQueryData> dataList = customDataDTO.getDatas();
        StringBuilder setValues = new StringBuilder();
        for (int i =0; i < dataList.size(); i++) {
            CustomColumnQueryData data = dataList.get(i);
            if (data.getColumnName() != null && !data.getColumnName().isEmpty()) {
                setValues.append(data.getColumnName());
                if (data.isLike()) {
                    setValues.append(" like '%").append(data.getColumnValue()).append("%'");
                } else {
                    setValues.append("=").append("'").append(data.getColumnValue()).append("'");
                }
                setValues.append((i<dataList.size() - 1) ? "," : "");
            }
        }
        List res = customRepository.queryAllDataByTableName(cusTableName , String.valueOf(setValues));
        return ApiResult.ok(res);
    }



    public ApiResult getPage(CustomDataQueryDTO customDataQueryDTO) {
        String cusTableName = customDataDTO.getTargetTable();
        List<CustomColumnQueryData> dataList = customDataQueryDTO.getDatas();
        StringBuilder setValues = new StringBuilder();
        for (int i =0; i < dataList.size(); i++) {
            CustomColumnQueryData data = dataList.get(i);
            if (data.getColumnName() != null && !data.getColumnName().isEmpty()) {
                setValues.append(data.getColumnName());
                if (data.isLike()) {
                    setValues.append(" like '%").append(data.getColumnValue()).append("%'");
                } else {
                    setValues.append("=").append("'").append(data.getColumnValue()).append("'");
                }
                setValues.append((i < dataList.size() - 1) ? "," : "");
            }
        }
        Page res = customRepository.queryPageDataByTableName(cusTableName , String.valueOf(setValues),  customDataQueryDTO.getSize(), customDataQueryDTO.getPage());
        return ApiResult.ok(res);
    }


    public ApiResult queryColumnNamesByTableName(CustomDataQueryDTO customDataQueryDTO) {
        String cusTableName = customDataDTO.getTargetTable();
        List<String> names;
        if (database.equals("MYSQL")) {
            names = customRepository.queryColumnNamesByTableNameMySQL(cusTableName);
        } else {
            names = customRepository.queryColumnNamesByTableNameOracle(cusTableName);
        }
        return ApiResult.ok(names);
    }

}

 

2. 新增Repository

import lombok.extern.slf4j.Slf4j;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Repository
public class CustomRepository {


    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    @Modifying
    @Query
    public int insertData(String sql) {
        log.info(" 请求的SQL: \n" + sql);
        return entityManager.createNativeQuery(sql).executeUpdate();
    }

    @Transactional
    @Modifying
    @Query
    public int insertDataAutoID(String cusTableName, String strColumns, String strValues) {
        StringBuilder sql = new StringBuilder();
        sql.append(" insert into ").append(cusTableName).append(" ( ").append(strColumns).append(") values ").append("( ").append(strValues).append(")");
        log.info(" 请求的SQL: " + sql);
        return entityManager.createNativeQuery(sql.toString()).executeUpdate();
    }

    @Transactional
    @Modifying
    @Query
    public int updateDataSetByID(String cusTableName, String setValues, long id) {
        StringBuilder sql = new StringBuilder();
        sql.append(" update ").append(cusTableName).append(" set ").append(setValues).append(" where ").append("( id = ").append(id).append(")");
        log.info(" 执行的SQL: " + sql);
        return entityManager.createNativeQuery(sql.toString()).executeUpdate();
    }

    @Transactional
    @Modifying
    @Query
    public int deleteDataSetByID(String cusTableName, String idSqlStr) {
        StringBuilder sql = new StringBuilder();
        sql.append(" delete from  ").append(cusTableName).append(" where   id in ( ").append(idSqlStr).append(")");
        log.info(" 执行的SQL: " + sql);
        return entityManager.createNativeQuery(sql.toString()).executeUpdate();
    }

    @Modifying
    @Query
    public List queryAllDataByTableName(String cusTableName, String whereCondition) {
        StringBuilder sql = new StringBuilder();
        sql.append(" select * from ").append(cusTableName);
        if (!whereCondition.isEmpty()) {
            sql.append(" where ").append(whereCondition);
        }
        javax.persistence.Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        log.info(" 执行的SQL: " + sql);
        return query.getResultList();
    }


    @Modifying
    @Query
    public Page queryPageDataByTableName(String cusTableName, String whereCondition, int size, int page) {
        StringBuilder countSql = new StringBuilder();
        countSql.append("select count(*) from ").append(cusTableName).append(" e ");
        if (!whereCondition.isEmpty()) {
            countSql.append(" where ").append(whereCondition);
        }
        StringBuilder sql = new StringBuilder();
        sql.append("select * from ").append(cusTableName);
        if (!whereCondition.isEmpty()) {
            sql.append(" where ").append(whereCondition);
        }
        log.info(" 执行的SQL: " + sql);
        Pageable pageable = PageRequest.of(page, size);
        return findWithPagination(pageable, sql.toString(), countSql.toString());
    }

    public Page findWithPagination(Pageable pageable, String sql, String countSql) {
        String countQuery = countSql;
        javax.persistence.Query cntQuery = entityManager.createNativeQuery(countQuery);
        BigInteger cnt = BigInteger.valueOf(0);
        Object countObj = cntQuery.getSingleResult();
        if (countObj instanceof BigDecimal) {
            cnt = BigInteger.valueOf(Integer.parseInt(String.valueOf(countObj)));
        } else {
            cnt = (BigInteger) cntQuery.getSingleResult();
        }
        javax.persistence.Query query = entityManager.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        query.setFirstResult((int) pageable.getOffset());
        query.setMaxResults(pageable.getPageSize());
        List list = query.getResultList();
        Page pageResult = new PageImpl<>(list, pageable, cnt.longValue());
        // 创建并返回一个Page对象
        return pageResult;
    }


    /**
     * 获取指定表的所有字段名称 MysqlDB
     * @param cusTableName 表名
     * @return 字段列名称
     */
    @Modifying
    @Query
    public List<String> queryColumnNamesByTableNameMySQL(String cusTableName) {
        StringBuilder sql = new StringBuilder();
        // oracle写法
        sql.append(" SHOW COLUMNS FROM ").append(cusTableName).append("");
        javax.persistence.Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        log.info(" 执行的SQL: " + sql);
        List<String> columns = new ArrayList<>();
        List<HashMap> resultList = query.getResultList();
        for (HashMap map : resultList) {
            String column =  map.get("Field").toString();
            columns.add(column);
        }
        log.info("所有的列名: " + columns);
        return columns;
    }


    /**
     * 获取指定表的所有字段名称 OracleDB
     * @param cusTableName 表名
     * @return 字段列名称
     */
    @Modifying
    @Query
    public List<String> queryColumnNamesByTableNameOracle(String cusTableName) {
        StringBuilder sql = new StringBuilder();
        // oracle写法
        sql.append(" SELECT  COLUMN_NAME FROM user_tab_columns  where TABLE_NAME = '").append(cusTableName).append("'");
        javax.persistence.Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        log.info(" 执行的SQL: " + sql);
        List<String> columns = new ArrayList<>();
        List<HashMap> resultList = query.getResultList();
        for (HashMap map : resultList) {
            String column =  map.get("COLUMN_NAME").toString();
            columns.add(column);
        }
        log.info("所有的列名: " + columns);
        return columns;
    }
}

 

3. 使用的Bean

@Data
@ApiModel("动态查询")
public class CustomDataQueryDTO {

    @ApiModelProperty(value = "目的表")
    private String targetTable;
    @ApiModelProperty(value = "每页显示多少数据")
    private int size;
    @ApiModelProperty(value = "查询第几页")
    private int page;
    @ApiModelProperty(value = "列名与Value值的集合")
    private List<CustomColumnQueryData> datas;

}


@Data
@ApiModel("列名与Value值的集合")
public class CustomColumnQueryData {
    @ApiModelProperty(value = "所需操作的字段")
    private String columnName;
    @ApiModelProperty(value = "字段对应的Value")
    private String columnValue;
    @ApiModelProperty(value = "是否是模糊查询,true为模糊查询,false为相等查询")
    private boolean like;
}



@Data
@ApiModel("数据新增/更新")
public class CustomDataCondition {

    @ApiModelProperty(value = "目的表")
    private String targetTable;

    @ApiModelProperty(value = "删除/编辑的目的表里的数据ID集合")
    private List<Long> idList;

    @ApiModelProperty(value = "新增/编辑时列名与Value值的集合")
    private List<CustomColumnData> datas;

}

@Data
@ApiModel("列名与Value值的集合")
public class CustomColumnData {
    @ApiModelProperty(value = "目标字段")
    private String columnName;
    @ApiModelProperty(value = "目标值")
    private String columnValue;
}

 

标签:hibernate,String,自定义,StringBuilder,Mysql,sql,import,data,append
From: https://www.cnblogs.com/uoky/p/18434929

相关文章

  • MySQL 在创建和删除用户时出现的ERROR 1396 (HY000)错误
    MySQL作为一个开源且广泛使用的关系型数据库管理系统,经常被用于处理各种的数据操作。在MySQL中,用户管理是非常重要的一个方面。尽管创建和删除用户在MySQL中是非常容易的,但是有时候会遇到ERROR1396(HY000)的错误。这个错误通常会在以下情况下发生:创建用户出现ERROR1396(HY000......
  • MySQL修改密码
    MySQL提供了各种可用于更改用户密码的语句,包括UPDATE,SETPASSWORD和GRANTUSAGE语句。方法1:使用UPDATE语句更改MySQL用户密码更改密码的第一种方法是使用UPDATE语句来更新mysql数据库的user表。执行UPDATE语句后,还需要执行FLUSHPRIVILEGES语句,从mysql数据库中的授权表中重新加......
  • PyQt项目实战-(Pyqt5+mysql制作一个TODO清单 第一部分)
    PyQt项目实战Pyqt5实现todolist工作待办的增、改、删、查功能,连接mysql存储数据(待办事项)。目录目录        1.界面设计    2.功能实现    3.界面各Button点击事件和槽函数的链接    4.mysql数据库操作工具类    5.槽函数实现......
  • 易优CMS请重启MYSQL数据库,或者联系空间服务商处理[错误报错·····]出现以下提示该
    当你遇到“请重启MYSQL数据库,或者联系空间服务商处理”的错误提示时,通常意味着数据库连接存在问题,可能是由于数据库服务未启动,或者是数据库配置信息不正确导致的。以下是一些基本的解决步骤:步骤1:检查数据库服务状态确认数据库服务是否启动如果你有访问服务器的权限,可以通......
  • MySQL 应对大量并发连接之道
    在当今的互联网时代,数据库面临着越来越多的并发连接请求。对于MySQL来说,如何有效地处理大量的并发连接成为了一个关键问题。本文将探讨MySQL处理大量并发连接的方法和策略。一、并发连接带来的挑战当MySQL数据库面临大量并发连接时,可能会出现以下问题:性能下降:大量的连接......
  • MySQL 中优化 COUNT()查询的实用指南
    在MySQL数据库的使用中,我们经常会用到COUNT()函数来统计行数或满足特定条件的行数。然而,在处理大规模数据时,COUNT()查询可能会变得非常缓慢,影响数据库的性能。那么,如何在MySQL中优化COUNT()查询呢?本文将为你介绍一些实用的方法。一、COUNT()函数的基本用法COUNT()函数是My......
  • mysql服务器无法启动怎么办
    当MySQL服务器无法启动时,你可以按照以下步骤进行排查和修复:检查错误日志:查看MySQL安装目录下的错误日志文件(通常是 host_name.err 或者 mysql.err 文件),里面会包含MySQL启动失败的具体原因。对于Linux系统,还可以查看系统的syslog日志。确认端口是否被占用:使用命令......
  • dedecms经常出现mysql"连接数据库失败,可能数据库密码不对
    遇到“DedeCms错误警告:连接数据库失败,可能数据库密码不对或数据库服务器出错”的错误信息时,可以采取以下步骤来排查和解决问题:1.检查数据库配置文件打开织梦CMS的数据库配置文件,通常位于 /data/common.inc.php 或 /include/config_database.php。检查数据库连接参数是否正......
  • ETL: 学习搭配PENTAHO-SERVER-CE-9.4.0.0-343 + MYSQL8.0.35 部分错误日志
     学习搭配PENTAHO-SERVER-CE-9.4.0.0-343+ MYSQL8.0.35 ,启动PENTAHO 后,日志显示:UsingCATALINA_BASE:"E:\Programs\pentaho-server\tomcat"UsingCATALINA_HOME:"E:\Programs\pentaho-server\tomcat"UsingCATALINA_TMPDIR:"E:\Programs......
  • Unity UI Tookite:实现命令控制台 [自定义元素]
    目录前言功能需求基础逻辑实现——输入输出分离逻辑实现——命令解析/历史指令切换历史指令解析指令基于反射的命令组自动装载逻辑实现——命令提示逻辑实现——定位报错逻辑实现——内容滚动/元素铺满逻辑实现——可变文本块最后前言最近在将Godot项目重写至Unit......