source: src/main/java/com/example/cookbook/repository/ReceptRepository.java

Last change on this file was 501396e, checked in by Blazho <aleksandar.blazhevski@…>, 9 months ago

added missing files

  • Property mode set to 100644
File size: 2.1 KB
Line 
1package com.example.cookbook.repository;
2
3
4import com.example.cookbook.dbConfig.DB;
5import com.example.cookbook.model.Recept;
6import org.springframework.stereotype.Repository;
7
8import java.sql.*;
9import java.util.ArrayList;
10import java.util.List;
11import java.util.Optional;
12
13@Repository
14public class ReceptRepository {
15
16
17 public List<Recept> findAll() throws SQLException {
18 Connection connection = DB.getConnection();
19
20 Statement stm = connection.createStatement();
21 String query = "select r.rec_id, r.rec_ime , r.postapka, avg(k.ocena) average\n" +
22 "from recepti r\n" +
23 " left join komentari k\n" +
24 " on r.rec_id = k.rec_id\n" +
25 "group by r.rec_id, r.rec_ime";
26 ResultSet result = stm.executeQuery(query);
27
28 List<Recept> recepti = new ArrayList<>();
29 while (result.next()){
30 Recept recept = new Recept();
31
32 recept.setRecId(result.getLong("rec_id"));
33 recept.setRecIme(result.getString("rec_ime"));
34 recept.setPostapka(result.getString("postapka"));
35 recept.setSrednaOcena(result.getFloat("average"));
36
37 recepti.add(recept);
38
39 }
40 stm.close();
41 result.close();
42 DB.closeConnection();
43 return recepti;
44 }
45
46 public Optional<Recept> findById(Long recId) throws SQLException {
47 Connection connection = DB.getConnection();
48
49 String query = "select * from recepti r where r.rec_id = ?";
50 PreparedStatement prepStm = connection.prepareStatement(query);
51 prepStm.setLong(1, recId);
52
53 ResultSet result = prepStm.executeQuery();
54 Recept recept = null;
55 if(result.next()){
56 recept = new Recept();
57 recept.setRecId(result.getLong("rec_id"));
58 recept.setRecIme(result.getString("rec_ime"));
59 recept.setPostapka(result.getString("postapka"));
60 }
61 result.close();
62 prepStm.close();
63 DB.closeConnection();
64 return Optional.ofNullable(recept);
65
66 }
67}
Note: See TracBrowser for help on using the repository browser.