MySQL Wildcard для “=” - там один

Наконец, у меня сработало следующее решение:

pom.xml:

<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-config -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-web -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>4.2.4.RELEASE</version>
    </dependency>

SecurityConfig.java

package com.Application;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    /* 
     * Method allow to access any resource without any authentication
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll();
    }
}

UrlFilter.java

package com.component;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

import com.daimler.datalayer.apistreamintegration.exception.BadRequest;

@Component
public class UrlFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger(UrlFilter.class);

    @Override
    public void init(FilterConfig filterChain) throws ServletException {

    }


    /* 
     * filter call to check if any double forward slash(//) present in URI before invoking Controller class 
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {

        LOGGER.info("Filtering the url");
        if (!(request instanceof HttpServletRequest)) {
            return;
        }
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        boolean isInvalidUrl = requestURI.contains("//");
        if (isInvalidUrl) {
            throw new BadRequest("The request was rejected because the URL was not normalized.");
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

BadRequest.java

package com.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequest extends RuntimeException {

  private static final long serialVersionUID = 1L;


  public BadRequest(String message) {
    super(message);
  }


  public BadRequest(String message, Throwable cause) {
    super(message, cause);
  }

}
18
задан Anthony 9 June 2011 в 17:17
поделиться

6 ответов

LIKE is basically the same as =, except LIKE lets you use wildcards.

These two queries will return the same results:

SELECT * FROM table WHERE col LIKE 'xyz';
SELECT * FROM table WHERE col='xyz';

Without a '%' in the LIKE query, it is effectively the same as '='.

If you're doing a selection on an integer column, you should consider using the IN() or BETWEEN operators. It sounds like you have two separate conditions that should be handled in your code however, rather than in the query, as your conditions dictate that you need at least two different kinds of queries.

Edit: I should clarify that LIKE and = are similar only in normal, humdrum string comparison usage. You should check the MySQL Manual for specifics on how it works, as there are situations where it's not the same (such as language sets).

13
ответ дан 30 November 2019 в 08:16
поделиться

Ответ зомбата великолепен, но я заметил только в его ответе, что вы выбираете целые числа. Он упомянул IN () и МЕЖДУ (). Вот примеры использования этих синтаксисов, а также некоторых других опций, которые у вас есть для целочисленного поля.

SELECT * FROM table WHERE col = 1;
SELECT * FROM table WHERE col BETWEEN 1 AND 12;
SELECT * FROM table WHERE col BETWEEN 6 AND 12;
SELECT * FROM table WHERE col <= 6;
SELECT * FROM table WHERE col < 6;
SELECT * FROM table WHERE col >= 6;
SELECT * FROM table WHERE col > 6;
SELECT * FROM table WHERE col <> 6;
SELECT * FROM table WHERE col IN (1,2,5,6,10);
SELECT * FROM table WHERE col NOT IN (1,2,5,6,10);
0
ответ дан 30 November 2019 в 08:16
поделиться

Если вы хотите выбрать все, почему вы вообще присоединяете предложение WHERE? Просто оставьте это условно, а не вставляйте в него подстановочный знак.

8
ответ дан 30 November 2019 в 08:16
поделиться

Причина использования LIKE заключается в том, что = не поддерживает подстановочные знаки. В противном случае не было бы причин для LIKE

7
ответ дан 30 November 2019 в 08:16
поделиться
SELECT * FROM table WHERE col RLIKE '.*'

то есть регулярное выражение LIKE.

0
ответ дан 30 November 2019 в 08:16
поделиться

Предполагая, что ваш запрос является параметризованным, оператор case, вероятно, целесообразно

select * from mytable
where col like case when @myvariable is null then % else myvariable end

Где @myvariable равно нулю, если вы не хотите использовать значение, в противном случае оно будет использовать целочисленное значение, которое вы передаете.

0
ответ дан 30 November 2019 в 08:16
поделиться
Другие вопросы по тегам:

Похожие вопросы: