java - 在 SQL 查询中使用 'true' 而不是 true 会产生意外结果

标签 java mysql sql hibernate entitymanager

我在使用 entityManager 对象运行 jpql 查询时发现了一些奇怪的东西。

我获取任何对象的 ID 号,其 boolean 字段对于列名 plantClimbs frostresistantspicy 为真

当 plantClimbs 为真时,我所做的方法生成如下所示的查询字符串

select u.id from SeedRecord u WHERE u.climbingPlant = 'true' 

当我运行这个查询时,我看到了一些意想不到的结果。它不是检索所有 climbingPlant 字段为真的 SeedRecord id,而是获取 climbingPlant 字段为假且 frostResistant 或 Spicy 字段恰好为真的种子记录的所有 id。

当我删除 true 周围的 ' 字符时,它会再次开始获取正确的 ID。我的问题是:为什么会这样?为什么将 ' 放在 true 周围似乎否定了一切,以至于 climbingPLant 字段为 false 的 seedrecords 实际上被获取了?

这是我的完整方法:

private Set<Long> findAllSeedRecordsByKeywordsOrBooleans(Set<String> checkKeywords, boolean plantClimbs, boolean teaPlant, boolean spicy){
    if (checkKeywords.isEmpty()
            && !plantClimbs
            && !spicy
            && !teaPlant) return Collections.EMPTY_SET;
    Set<String> availablePlantTypes = new HashSet<>();
    Set<String> availableProduceTypes = new HashSet<>();
    log.info("fetching entitymanager");
    EntityManager entityManager = seedRecordDao.getEntityManager();
    Map<String,Set<String>> containsProduceNameKeyword = new HashMap<>();
    Map<String,Set<PlantType>> containsPlantTypeKeyword = new HashMap<>();
    Map<String,Set<ProduceType>> containsProduceTypeKeyword = new HashMap<>();
    Set<String> searchProduceNames = new HashSet<>();
    Set<PlantType> searchPlantTypes = new HashSet<>();
    Set<ProduceType> searchProduceTypes = new HashSet<>();
    boolean hasPriorCondition = false;
    boolean produceNamesConditionApplied = false;
    boolean produceTypesConditionApplied = false;
    boolean plantTypesConditionApplied = false;

    StringBuilder filterQuery = new StringBuilder("select u.id from SeedRecord u WHERE ");
    if(!checkKeywords.isEmpty()) {
        log.info("getting the producenames");
        Set<String> availableProduceNames = seedRecordDao.getProduceNames()
                .stream().map(ProduceName::getProduceName).collect(Collectors.toSet());
        for (PlantType plantType : PlantType.values())
            availablePlantTypes.add(plantType.toString());
        for (ProduceType produceType : ProduceType.values())
            availableProduceTypes.add(produceType.toString());
        for (String keyword : checkKeywords) {
            if (availableProduceNames.contains(keyword)) {
                searchProduceNames.add(keyword);
                if (!produceNamesConditionApplied) {
                    if (!hasPriorCondition) {
                        filterQuery.append("u.produceName IN :produceNames ");
                        hasPriorCondition = true;
                    } else
                        filterQuery.append("OR u.produceName IN :produceNames ");
                    produceNamesConditionApplied = true;
                }
            } else if (availablePlantTypes.contains(keyword)) {
                searchPlantTypes.add(PlantType.valueOf(keyword));
                if (!plantTypesConditionApplied) {
                    if (!hasPriorCondition) {
                        filterQuery.append("u.plantType IN :plantTypes ");
                        hasPriorCondition = true;
                    } else
                        filterQuery.append("OR u.plantType IN :plantTypes ");
                    plantTypesConditionApplied = true;
                }
            } else if (availableProduceTypes.contains(keyword)) {
                searchProduceTypes.add(ProduceType.valueOf(keyword));
                if (!produceTypesConditionApplied) {
                    if (!hasPriorCondition) {
                        filterQuery.append("u.produceType IN :produceTypes ");
                        hasPriorCondition = true;
                    } else
                        filterQuery.append("OR u.produceType IN :produceTypes ");
                    produceTypesConditionApplied = true;
                }
            }
        }

        if (!searchProduceNames.isEmpty())
            containsProduceNameKeyword.put("produceNames", searchProduceNames);
        if (!searchProduceTypes.isEmpty())
            containsProduceTypeKeyword.put("produceTypes", searchProduceTypes);
        if (!searchPlantTypes.isEmpty())
            containsPlantTypeKeyword.put("plantTypes", searchPlantTypes);
    }

    if(plantClimbs)
        if (!hasPriorCondition) {
            filterQuery.append("u.climbingPlant = 'true' ");
            hasPriorCondition = true;
        }
        else
            filterQuery.append("OR u.climbingPlant = 'true' ");
    if(teaPlant)
        if (!hasPriorCondition) {
            filterQuery.append("u.teaPlant = 'true' ");
            hasPriorCondition = true;
        }
        else
            filterQuery.append("OR u.teaPlant = 'true' ");
    if(spicy)
        if (!hasPriorCondition) {
            filterQuery.append("u.spicy = 'true' ");
        }
        else
            filterQuery.append("OR u.spicy = 'true' ");
    try {
        log.info("preparing query");
        log.info(filterQuery.toString());
        TypedQuery<Long> query = entityManager.createQuery(filterQuery.toString(), Long.class);
        if (!containsProduceNameKeyword.isEmpty())
            containsProduceNameKeyword.forEach((parameter, input) -> query.setParameter(parameter, input));
        if (!containsPlantTypeKeyword.isEmpty())
            containsPlantTypeKeyword.forEach((parameter, input) -> query.setParameter(parameter, input));
        if (!containsProduceTypeKeyword.isEmpty())
            containsProduceTypeKeyword.forEach((parameter, input) -> query.setParameter(parameter, input));
        log.info("sending to database NOW");
        return new HashSet<>(query.getResultList());
    }
    catch(Exception e){
        throw e;
    }
}

最佳答案

这是因为你的 climbingPlant 列是 boolean 值,所以 MySQL 必须将 'true' 转换为 boolean 值才能与之比较,这是(并且对于任何字符串)false .因此,当您在引号中包含 true 时,当 climbingPlant 为 false 时,它​​匹配 climbingPlant。其他列的值无关紧要。对于演示,试试这个:

select 'true' = true, 'true' = false, 'anything' = false

输出:

'true' = true   'true' = false  'anything' = false  
0               1               1

关于java - 在 SQL 查询中使用 'true' 而不是 true 会产生意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51786281/

相关文章:

java - 返回 boolean 值而不是在 Java 中声明 void 类型?

java - 测试@ConditionalOnClass自动配置

JAVA:控制音频输入流的音量

sql - 当只有某些行是有效的正则表达式时,Postgres : select using column as regex,

php - 使用空值将动态数组插入到 MySQL 数据库中

java - Hibernate锁导致脏收集异常

mysql - 如何在 sails.js 应用程序中编写数据库迁移

mysql - 为什么我在单个自引用表的事务中遇到 MySQL 外键插入约束违规?

php - Laravel 表间迁移引用

sql - 不同的多列