Skip to content

Commit

Permalink
feat: 채팅 저장을 jdbc template을 이용한 bulk insert 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
Curry4182 committed Apr 15, 2024
1 parent b6c186a commit 2b27e86
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.programmers.lime.domains.chat.domain.Chat;
import com.programmers.lime.domains.chat.model.ChatInfo;
import com.programmers.lime.domains.chat.repository.ChatJdbcTemplateRepository;
import com.programmers.lime.domains.chat.repository.ChatRepository;

import lombok.RequiredArgsConstructor;
Expand All @@ -17,6 +19,8 @@ public class ChatAppender {

private final ChatRepository chatRepository;

private final ChatJdbcTemplateRepository chatJdbcTemplateRepository;

public void appendChat(
final ChatInfo chatInfo
) {
Expand Down Expand Up @@ -45,6 +49,6 @@ public void appendChats(
.build()
).collect(Collectors.toList());

chatRepository.saveAll(chats);
chatJdbcTemplateRepository.bulkInsertChats(chats);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.programmers.lime.domains.chat.repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.programmers.lime.domains.chat.domain.Chat;

import lombok.RequiredArgsConstructor;

@Repository
@RequiredArgsConstructor
public class ChatJdbcTemplateRepository {

private static final String INSERT_SQL = "INSERT INTO chats (chat_room_id, member_id, message, send_at, chat_type) VALUES (?, ?, ?, ?, ?)";

private final JdbcTemplate jdbcTemplate;

@Transactional
public void bulkInsertChats(final List<Chat> chats) {
jdbcTemplate.batchUpdate(INSERT_SQL, chats, 50, this::prepareStatement);
}

private void prepareStatement(final PreparedStatement ps, final Chat chat) throws SQLException {
ps.setLong(1, chat.getChatRoomId());
ps.setLong(2, chat.getMemberId());
ps.setString(3, chat.getMessage());
ps.setTimestamp(4, Timestamp.valueOf(chat.getSendAt()));
ps.setString(5, chat.getChatType().toString());
}
}

0 comments on commit 2b27e86

Please sign in to comment.