Skip to content
Snippets Groups Projects
Commit d8ecfccb authored by Beth Davies's avatar Beth Davies
Browse files

Replace JPA with JDBC

parent a896cb49
Branches
No related tags found
No related merge requests found
package polish_community_group_11.polish_community.comments.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import polish_community_group_11.polish_community.comments.models.Comment;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class CommentJdbcRepository implements CommentRepository {
private final JdbcTemplate jdbcTemplate;
@Autowired
public CommentJdbcRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Comment save(Comment comment) {
String sql = "INSERT INTO comment (comment_content, user_id, post_title, created_date) VALUES (?, ?, ?, ?)";
jdbcTemplate.update(sql,
comment.getContent(),
comment.getUserId(),
comment.getPostTitle(),
comment.getCreatedDate()
);
// Retrieve the last inserted ID
Integer commentId = jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", Integer.class);
comment.setId(commentId);
return comment;
}
public List<Comment> findByPostTitle(String postTitle) {
String sql = "SELECT c.id, c.comment_content, c.user_id, c.post_title, c.created_date, " +
"u.fullname as username, u.email as user_email " +
"FROM comment c " +
"JOIN users u ON c.user_id = u.id " +
"WHERE c.post_title = ?";
return jdbcTemplate.query(sql, new Object[]{postTitle}, new RowMapper<Comment>() {
@Override
public Comment mapRow(ResultSet rs, int rowNum) throws SQLException {
Comment comment = new Comment();
comment.setId(rs.getInt("comment_id"));
comment.setContent(rs.getString("comment_content"));
comment.setUserId(rs.getInt("user_id"));
comment.setPostTitle(rs.getString("post_title"));
comment.setCreatedDate(rs.getTimestamp("created_date").toLocalDateTime());
return comment;
}
});
}
}
\ No newline at end of file
package polish_community_group_11.polish_community.comments.models;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class CommentResponse {
private String content;
private String postTitle;
private String createdDate;
private String username;
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment