- Timestamp:
- 02/03/24 15:58:58 (9 months ago)
- Branches:
- master
- Children:
- aea04dd
- Parents:
- 3e572eb
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
src/main/java/com/example/cookbook/repository/ReceptRepository.java
r3e572eb r501396e 1 package com.example.cookbook.repository;public class ReceptRepository { 1 package com.example.cookbook.repository; 2 3 4 import com.example.cookbook.dbConfig.DB; 5 import com.example.cookbook.model.Recept; 6 import org.springframework.stereotype.Repository; 7 8 import java.sql.*; 9 import java.util.ArrayList; 10 import java.util.List; 11 import java.util.Optional; 12 13 @Repository 14 public 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 } 2 67 }
Note:
See TracChangeset
for help on using the changeset viewer.