在SQL查询中使用“ true”相对于true会产生意外结果

时间:2018-08-10 12:12:54

标签: java mysql sql hibernate entitymanager

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

我获取列名plantClimbs frostresistantspicy的布尔字段为true的所有对象的ID号

当plantClimbs为true时,我制作的方法将使查询字符串看起来像这样

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

当我运行此查询时,我看到一些意外结果。而不是检索所有climbingPlant字段为true的SeedRecord id,而是获取所有其climbingPlant字段为false且frostResistant或Spicy字段为true的种子记录的id。

当我删除'true周围的字符时,它开始再次获取正确的ID。我的问题是:为什么会这样?为什么将'设置为true似乎会否定一切,以便实际上取回攀爬字段为false的种子记录?

这里是我的完整方法:

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;
    }
}

1 个答案:

答案 0 :(得分:4)

这是因为您的climbingPlant列为布尔值,因此MySQL必须将'true'强制转换为布尔值才能与它进行比较,这(对于任何字符串都是错误的)。因此,如果您将true括在引号中,则climbingPlant为假时,它将与climbingPlant匹配。其他列的值无关紧要。对于演示,请尝试以下操作:

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

输出:

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