Skip to content

Commit d5a02bb

Browse files
Adds a search input (searches by Restaurant name).
1 parent 85d0d2a commit d5a02bb

File tree

3 files changed

+31
-5
lines changed

3 files changed

+31
-5
lines changed

src/main/java/dev/drugowick/jpaqueriesblogpost/infrastructure/repository/RestaurantRepository.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,9 @@
33
import dev.drugowick.jpaqueriesblogpost.domain.model.Restaurant;
44
import org.springframework.data.jpa.repository.JpaRepository;
55

6+
import java.util.List;
7+
68
public interface RestaurantRepository extends JpaRepository<Restaurant, Long> {
9+
10+
List<Restaurant> findAllByNameContaining(String query);
711
}

src/main/java/dev/drugowick/jpaqueriesblogpost/web/pages/IndexPage.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import org.springframework.stereotype.Controller;
55
import org.springframework.ui.Model;
66
import org.springframework.web.bind.annotation.RequestMapping;
7+
import org.springframework.web.bind.annotation.RequestParam;
78

89
@Controller
910
public class IndexPage {
@@ -19,4 +20,16 @@ public String index(Model model) {
1920
model.addAttribute("restaurants", restaurantRepository.findAll());
2021
return "index";
2122
}
23+
24+
@RequestMapping("/search")
25+
public String indexWithQuery(@RequestParam("query") String query,
26+
@RequestParam("field") String field,
27+
Model model) {
28+
if (field.equals("name")) {
29+
model.addAttribute("restaurants", restaurantRepository.findAllByNameContaining(query));
30+
}
31+
model.addAttribute("field", field);
32+
model.addAttribute("query", query);
33+
return "index";
34+
}
2235
}

src/main/resources/templates/index.html

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,24 @@
77
<body>
88
<h1>Restaurants</h1>
99

10+
<form th:action="@{/search}">
11+
Search by:
12+
<select name="field">
13+
<option value="name">Name</option>
14+
</select>
15+
<input placeholder="Your search query" th:name="query" th:value="${query}" type="text"/>
16+
<input type="submit" value="Search">
17+
</form>
18+
1019
<br><br>
1120

1221
<table>
1322
<thead>
14-
<tr bgcolor="#d3d3d3">
15-
<td>Name</td>
16-
<td>Address</td>
17-
<td>Delivery Fee</td>
18-
<td>Cuisine</td>
23+
<tr bgcolor="#d3d3d3">
24+
<td>Name</td>
25+
<td>Address</td>
26+
<td>Delivery Fee</td>
27+
<td>Cuisine</td>
1928
</tr>
2029
</thead>
2130
<tr th:each="restaurant : ${restaurants}" style="cursor: pointer" th:onclick="'window.location.href=\'/restaurants/' + ${restaurant.getId()} + '\''">

0 commit comments

Comments
 (0)