WEB/Server

[SpringBoot+JDBC] sql like ์ฟผ๋ฆฌ๋ฌธ ์‚ฌ์šฉํ•˜๊ธฐ

kite707 2022. 1. 25.

ํ”„๋กœ์ ํŠธ ๋„์ค‘ ๊ฒ€์ƒ‰ ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด like ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ–ˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ like๋ฌธ์˜ ์ฟผ๋ฆฌ๋ฌธ ๋ฌธ๋ฒ•์€ ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

--A๋ฅผ ํฌํ•จํ•˜๋Š” ๋ฌธ์ž ์ฐพ๊ธฐ--
SELECT ์ปฌ๋Ÿผ๋ช… FROM ํ…Œ์ด๋ธ” WHERE ์ปฌ๋Ÿผ๋ช… LIKE '%A%'

๊ทธ๋Ÿฐ๋ฐ Springboot ๋‚ด์—์„œ๋Š” ์ฟผ๋ฆฌ๋ฌธ์„ ์•„๋ž˜์™€ ๊ฐ™์ด ํฐ ๋”ฐ์˜ดํ‘œ("")๋กœ ๋ฌถ๋Š”๋‹ค.

//MovieDao ํŒŒ์ผ
public Writer getWriter(int userIdx) {
        //sql๋ฌธ
        String getUserQuery = "select user_idx,nickname,photo from user where user_idx=?;";
        int param=userIdx;
        return this.jdbcTemplate.queryForObject(getUserQuery,
                (rs, rowNum) -> new Writer(
                        rs.getInt("user_idx"),
                        rs.getString("nickname"),
                        rs.getString("photo")),
                param);

    }

 

๊ทธ๋ž˜์„œ ๊ทธ๋ƒฅ like๋ฌธ์„ ์‚ฌ์šฉํ•˜๋ฉด ์—๋Ÿฌ๊ฐ€ ๋‚œ๋‹ค. SpringBoot์—์„œ sql๋ฌธ ๋‚ด ?๋Š” ์ž‘์€ ๋”ฐ์˜ดํ‘œ๋กœ ๊ฐ์‹ธ์ ธ ์น˜ํ™˜๋˜๋ฏ€๋กœ ๊ฒ€์ƒ‰ํ•˜๊ณ ์ž ํ•˜๋Š” ๋‚ด์šฉ์„ %%๋กœ ๊ฐ์‹ธ์„œ ?์— ๋„ฃ์–ด์ฃผ๋ฉด ๋œ๋‹ค. ์•„๋ž˜๋Š” ์‚ฌ์šฉ ์˜ˆ์‹œ์ด๋‹ค.

public List<GetMovieInfo> getMovieIdx_Search(String keyword,String sort){
        String query="SELECT movie_idx FROM movie where movie_title like ? ";
        //๊ฒ€์ƒ‰ํ•˜๊ณ ์ž ํ•˜๋Š” ํ‚ค์›Œ๋“œ๋ฅผ %%๋กœ ๊ฐ์‹ธ์ค€๋‹ค.
        String param="%"+keyword+"%";
        return this.jdbcTemplate.query(query,
                (rs, rowNum) -> new GetMovieInfo(
                        rs.getInt("movie_idx")),param);
    }

์œ„์™€ ๊ฐ™์ด SpringBoot์—์„œ like๋ฌธ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

๋Œ“๊ธ€