728x90
반응형
📌 TIL (Today I Learned) - 2025-02-12
1. JPA 연관관계 (1:N, N:1)
@ManyToOne
을 B 엔티티에서 A 엔티티에 설정하면 B가 N, A가 1인 관계가 된다.즉, A(1) ↔ B(N) 관계를 의미하며, B가 A의 외래 키(FK)를 가지게 된다.
@Entity class B( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null, @ManyToOne @JoinColumn(name = "a_id") val a: A )
@Entity
class A(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
@OneToMany(mappedBy = "a")
val bs: List<B> = mutableListOf()
)
### 2. **`@SQLRestriction`이란?**
- Hibernate에서 **엔티티 단위로 SQL WHERE 절을 적용**할 수 있도록 해주는 어노테이션.
- 특정 필드에만 필터를 적용할 때 유용하다.
```kotlin
@Entity
class User(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null,
val name: String,
val isDeleted: Boolean = false,
@SQLRestriction("is_deleted = false")
val status: String
)
- 삭제되지 않은 데이터만 자동 필터링됨.
✅ @Where
vs @SQLRestriction
어노테이션 | 적용 대상 | 특징 |
---|---|---|
@SQLRestriction |
필드 단위 | 특정 필드에만 조건 적용 가능 |
@Where |
엔티티 단위 | 엔티티 전체에 WHERE 조건 적용 |
### 3. Java 스트림으로 특정 값 필터링 |
0
을 제외하고 리스트 필터링List<Integer> filteredList = list.stream() .filter(num -> num != 0) .collect(Collectors.toList());
배열에서
0
을 제외하고 필터링int[] filteredArray = Arrays.stream(scores) .filter(i -> i != 0) .toArray();
4. Java에서 특정 값의 인덱스 반환
- 배열에서
0이 아닌 값의 인덱스
반환 (1-based index)int[] indices = IntStream.range(0, scores.length) .filter(i -> scores[i] != 0) .map(i -> i + 1) .toArray();
5. 최고 점수를 가진 사람의 인덱스 찾기
scores
배열에서 최고 점수를 가진 사람만 필터링하는 방법int maxScore = Arrays.stream(scores).max().orElse(0);
int[] topScorers = IntStream.range(0, scores.length)
.filter(i -> scores[i] == maxScore)
.map(i -> i + 1)
.toArray();
✅ **최고 점수의 인덱스를 반환하면서 1-based로 변환**
### 6. **리팩토링 포인트**
- 중복된 배열(`one`, `two`, `three`)을 **2차원 배열(`patterns`)**로 정리.
- **점수 계산 / 최고 점수 찾기 / 상위 득점자 찾기** 로직을 각각 함수로 분리.
```java
public int[] solution(int[] answers) {
int[][] patterns = {
{1, 2, 3, 4, 5},
{2, 1, 2, 3, 2, 4, 2, 5},
{3, 3, 1, 1, 2, 2, 4, 4, 5, 5}
};
int[] scores = calculateScores(answers, patterns);
int maxScore = findMaxScore(scores);
return findTopScorers(scores, maxScore);
}
private int[] calculateScores(int[] answers, int[][] patterns) {
int[] scores = new int[patterns.length];
for (int i = 0; i < answers.length; i++) {
for (int j = 0; j < patterns.length; j++) {
if (patterns[j][i % patterns[j].length] == answers[i]) {
scores[j]++;
}
}
}
return scores;
}
private int findMaxScore(int[] scores) {
return Arrays.stream(scores).max().orElse(0);
}
private int[] findTopScorers(int[] scores, int maxScore) {
return IntStream.range(0, scores.length)
.filter(i -> scores[i] == maxScore)
.map(i -> i + 1)
.toArray();
}
✅ 가독성, 유지보수성 향상! 🚀
728x90
반응형
'Blog > TIL' 카테고리의 다른 글
2025-02-14 (금) (0) | 2025.02.14 |
---|---|
2025-02-13 (목) (2) | 2025.02.13 |
2025-02-11 (화) (0) | 2025.02.11 |
2025-02-10 (월) (0) | 2025.02.10 |
2025-02-06 (목) (2) | 2025.02.06 |
댓글