1 | package com.example.cookbook.repository;
|
---|
2 |
|
---|
3 |
|
---|
4 | import com.example.cookbook.dbConfig.DB;
|
---|
5 | import com.example.cookbook.model.Komentar;
|
---|
6 | import org.springframework.stereotype.Repository;
|
---|
7 |
|
---|
8 | import java.sql.*;
|
---|
9 | import java.time.LocalDateTime;
|
---|
10 | import java.util.ArrayList;
|
---|
11 | import java.util.List;
|
---|
12 |
|
---|
13 | @Repository
|
---|
14 | public class KomentariRepository {
|
---|
15 |
|
---|
16 | public List<Komentar> findAllByRecId(Long recId) throws SQLException {
|
---|
17 | Connection connection = DB.getConnection();
|
---|
18 |
|
---|
19 | String query = "select k.kom_data, k.telefon, k.rec_id, k.ocena, k.text, korisnici.kor_ime, korisnici.prezime\n" +
|
---|
20 | "from komentari k\n" +
|
---|
21 | " left join korisnici on k.telefon = korisnici.telefon\n" +
|
---|
22 | "where rec_id = ?;";
|
---|
23 |
|
---|
24 | PreparedStatement prepStm = connection.prepareStatement(query);
|
---|
25 | prepStm.setLong(1, recId);
|
---|
26 |
|
---|
27 | ResultSet result = prepStm.executeQuery();
|
---|
28 | List<Komentar> komentari = new ArrayList<>();
|
---|
29 |
|
---|
30 | while (result.next()){
|
---|
31 | Komentar komentar = new Komentar();
|
---|
32 | komentar.setKomData(result.getObject("kom_data", LocalDateTime.class));
|
---|
33 | komentar.setTelefon(result.getString("telefon"));
|
---|
34 | komentar.setRecId(result.getLong("rec_id"));
|
---|
35 | komentar.setOcena(result.getInt("ocena"));
|
---|
36 | komentar.setText(result.getString("text"));
|
---|
37 | komentar.setImePrezime(result.getString("kor_ime") + " " + result.getString("prezime"));
|
---|
38 | komentari.add(komentar);
|
---|
39 | }
|
---|
40 |
|
---|
41 | result.close();
|
---|
42 | prepStm.close();
|
---|
43 | DB.closeConnection();
|
---|
44 |
|
---|
45 | return komentari;
|
---|
46 | }
|
---|
47 |
|
---|
48 | public void save(Komentar komentar) throws SQLException {
|
---|
49 | Connection connection = DB.getConnection();
|
---|
50 |
|
---|
51 | String query = "insert into komentari (kom_data, telefon, rec_id, ocena, text) values \n" +
|
---|
52 | " (?, ?, ?, ?, ?);";
|
---|
53 |
|
---|
54 | PreparedStatement prepStm = connection.prepareStatement(query);
|
---|
55 | prepStm.setObject(1, komentar.getKomData());
|
---|
56 | prepStm.setString(2, komentar.getTelefon());
|
---|
57 | prepStm.setLong(3, komentar.getRecId());
|
---|
58 | prepStm.setInt(4, komentar.getOcena());
|
---|
59 | prepStm.setString(5, komentar.getText());
|
---|
60 |
|
---|
61 | prepStm.executeUpdate();
|
---|
62 |
|
---|
63 | prepStm.close();
|
---|
64 | DB.closeConnection();
|
---|
65 | }
|
---|
66 | }
|
---|