250x250
๋ฐ์ํ
Notice
Recent Posts
Recent Comments
Link
์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- ngrok
- js
- AWS
- Jenkins
- Express
- error
- github
- python
- docker
- 500
- Java
- RDS
- Spring
- Troubleshooting
- TypeScript
- axios
- MUI
- nodejs
- macbook
- webhook
- React
- javascript
- springboot
- EC2
- fastapi
- deploy
- Github Actions
- linux
- AWS EC2
- MongoDB
Archives
- Today
- Total
BEAT A SHOTGUN
[SPRING] FOR ๋ฅผ ์ด์ฉํด SQL๋ฌธ์ผ๋ก๋ ๋ฟ์ ์ ์๋ ENTITY ๋ด๋ถ ๊ฒ์ํ๊ธฐ ๋ณธ๋ฌธ
PROJECT
[SPRING] FOR ๋ฅผ ์ด์ฉํด SQL๋ฌธ์ผ๋ก๋ ๋ฟ์ ์ ์๋ ENTITY ๋ด๋ถ ๊ฒ์ํ๊ธฐ
thovy 2022. 10. 27. 02:56728x90
๋ฐ์ํ
SMALL
๐คทโโ๏ธ SITUATION
POST ENTITY ๋ EMOTION ENTITY ๋ฅผ ์ฌ๋ฌ๊ฐ ๊ฐ๊ณ ์๋ค. ๊ทธ๋์ List
์ด Post ์ ์๋ค. // Post.java public class Post{ ... @ManyToMany(fetch = FetchType.EAGER) @JoinColumn(name = "emotionId", referencedColumnName = "emotionId") private List<Emotion> emotion; }
- List ๋ SQL ์์ ์ธ์ํ์ง ๋ชปํ๋ค.
๐ค What I Want
Search!
word
๋ฅผ ์ ๋ ฅํ๋ฉดtitle
,contents
๊ทธ๋ฆฌ๊ณemotion ์ ์๋ emotionword
์word
๊ฐ ํฌํจ๋post
๋ฅผ ๊ฒ์ํ๊ณ ์ถ๋ค!- sql ๋ฌธ์ ์์ฑํ์
SELECT * FROM post WHERE TITLE LIKE %:search% OR CONTENTS LIKE %:search% OR EMOTION.EMOTIONWORD LIKE %:search%
// PostRepository.java
@Query(value = "SELECT * FROM post WHERE TITLE LIKE %:search% OR CONTENTS LIKE %:search% OR EMOTION.EMOTIONWORD LIKE %:search%", nativeQuery = true)
public List
3. ์๋์ง!โ
# โ ERROR
## HIBERNATE CAN'T FIND `"EMOTION"`
# โ
SOLUTION
## KEYSET + contains ๐ฒ
๊ทธ๋์ ๊ณ ๋ฏผ ๋์
1. SQL ์
`SELECT * FROM post WHERE TITLE LIKE %:search% OR CONTENTS LIKE %:search%`
์ด๋ ๊ฒ ์ฐ๊ณ
2. KEYSET ์ ์ด์ฉํ ๋ค contains โ
```java
// PostServiceImpl.java
public List<Post> findByWord(String word){
List<Post> postList = postRepository.findBySearch(word);
โจโจ
for(Post posttmp : postRepository.findAll()){
for (Emotion emotiontmp : posttmp.getEmotion()){
if(emotiontmp.getEmotionWord().contains(search)){
postList.add(posttmp);
}
}
}
โจโจ
return postList;
}
๋
์ด๋ ๊ฒ sql ์ด ํด๊ฒฐํ ์ ์๋ค๋ฉด java ๊ฐ ํด๊ฒฐํด์ค๋ค.
์ด๋ ๊ฒ ํ๋ ์ํํ์ง ๋ง์!
WHY "KEYSET"
keyset ์ด ์ ์ผ ๋น ๋ฅด๊ณ ๊ฐํธํ๋ค. ์ฐธ๊ณ
์ถํ์ post ๊ฐ ๋ง์์ก์ ๋ findAll ํ posts ๋ฅผ ๋ชจ๋ for๋ฌธ ๋๋ฆฌ๋ ค๋ฉด ์์ฒญ ์ค๋๊ฑธ๋ฆดํ ๋ฐ ์ ์ผ ๋น ๋ฅธ ๊ฑฐ ์จ์ผ์ง!
ํ๋ณตํ๋ค.
์ด์ฉ๋ฉด ๋๋ ์์ฃผ ๋ฉ์ฒญ์ด๋ ์๋์ง๋...?
728x90
๋ฐ์ํ
LIST
'PROJECT' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Comments