Post

(feat) How to get average score

βœ… get average score

score is in review table get all reviews of a movie, set it in reviewList for each reviewList, get score and add. sum() then, get size of reviewList average= sum of review scores / size of reviewList

🟒 get average score

1
2
int scoreSum= reviewList.stream().mapToInt(Review::getScore).sum();
int numberOfReviews= reviewList.size();

🟒 Final Code

μ—¬λŸ¬λ²ˆ μ‚¬μš©ν•΄μ„œ λ‹€λ₯Έ λ©”μ†Œλ“œμ—μ„œ κ΅¬ν˜„

1
2
3
4
5
6
7
8
    private double caculateScore(List<Review> reviewList){
        //score(review) λ‹€ λ”ν•΄μ„œ / number of review
        int scoreSum= reviewList.stream().mapToInt(Review::getScore).sum();
        int numberOfReviews=reviewList.size();
        double scoreAvg= (double) scoreSum/numberOfReviews;
        double formattedScoreAvg= Math.round(scoreAvg+10.0)/10.0;
        return scoreAvg;
    }

🟒 Cleaner Code

같은 λ©”μ†Œλ“œ λ‚΄μ—μ„œ κ΅¬ν˜„ πŸ’‘ λ‚˜λˆ„κΈ° ν•  λ•ŒλŠ” 항상 λ‚˜λˆ„λŠ” μˆ˜κ°€ 0이 λ˜μ§€ μ•Šλ„λ‘ 쑰심해야 ν•œλ‹€.

1
2
3
4
5
6
7
8
9
10
11
12
        Page<Movie> moviePage= movieJpa.findAll(pageable);
        for(Movie movie: moviePage){
            //scoreAvg
            List<Review> reviewList= reviewJpa.findByMovieId(movie.getMovieId());
            int scoreSum= reviewList.stream().map(Review::getScore).mapToInt(Integer::intValue).sum();
            int countReview= reviewList.size();
            if(countReview == 0 )throw new NotFoundException("There are no reviews for this movie"); //λ‚˜λˆ„λŠ” 수 0 ❌
            double scoreAvg= (double) scoreSum / countReview * 100;

            movie.setScoreAvg(scoreAvg);
            movieJpa.save(movie);
        }

🟒 JPAμ—μ„œ κ΅¬ν•˜λŠ” 방법

movie tableμ•ˆμ— score_avgλΌλŠ” field있음
λ”°λΌμ„œ JPAμ—μ„œ κ΅¬ν•΄μ„œ movie tableμ•ˆμ— score_avgλ₯Ό update

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Repository
public interface MovieJpa extends JpaRepository<Movie, Integer> {

    @Transactional
    @Modifying
    @Query(
            value = "UPDATE movie AS A " +
                    "INNER JOIN (SELECT movie_id, (count(score) / sum(score)) AS SCORE_AVG " +
                    "            FROM review group by movie_id) AS B ON A.movie_id = B.movie_id " +
                    " SET A.score_avg = B.SCORE_AVG "
    , nativeQuery = true)
    void updateScoreAvg();

    Page<Movie> findAll(Pageable pageable);
}
This post is licensed under CC BY 4.0 by the author.