Skip to content
This repository has been archived by the owner on Oct 21, 2024. It is now read-only.

Commit

Permalink
spring-action: implementing embedded DBB
Browse files Browse the repository at this point in the history
  • Loading branch information
MarioCodes committed Oct 2, 2019
1 parent 9d7fe0c commit b6f2ed3
Show file tree
Hide file tree
Showing 12 changed files with 255 additions and 67 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package es.msanchez.spring.springinaction.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {
"es.msanchez.spring.springinaction.**"
})
public class SpringConfig {
}
Original file line number Diff line number Diff line change
@@ -1,27 +1,54 @@
package es.msanchez.spring.springinaction.controllers;

import es.msanchez.spring.springinaction.dao.IngredientRepository;
import es.msanchez.spring.springinaction.dao.TacoRepository;
import es.msanchez.spring.springinaction.entities.Ingredient;
import es.msanchez.spring.springinaction.entities.Order;
import es.msanchez.spring.springinaction.entities.Taco;
import es.msanchez.spring.springinaction.enums.Type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/design")
@SessionAttributes("order")
public class DesignTacoController {

private final IngredientRepository ingredientRepository;
private final TacoRepository tacoRepository;

/**
* @param ingredientRepository injected
* @param tacoRepository injected
*/
@Autowired
public DesignTacoController(IngredientRepository ingredientRepository, TacoRepository tacoRepository) {
this.ingredientRepository = ingredientRepository;
this.tacoRepository = tacoRepository;
}

@ModelAttribute(name = "order")
public Order order() {
return new Order();
}

@ModelAttribute(name = "taco")
public Taco taco() {
return new Taco();
}

/**
* This is going to be loaded every time we load for "design" view.
*
Expand All @@ -30,16 +57,16 @@ public class DesignTacoController {
@ModelAttribute
public void addIngredientsToModel(final Model model) {
final List<Ingredient> ingredients = Arrays.asList(
new Ingredient("FLTO", "Flour tortilla", Type.WRAP),
new Ingredient("COTO", "Corn tortilla", Type.WRAP),
new Ingredient("GRBF", "Ground Beef", Type.PROTEIN),
new Ingredient("CARN", "Carnitas", Type.PROTEIN),
new Ingredient("TMTO", "Diced tomatoes", Type.VEGGIES),
new Ingredient("LETC", "Lettuce", Type.VEGGIES),
new Ingredient("CHED", "Ceddar", Type.CHEESE),
new Ingredient("JACK", "Monterrey Jack", Type.CHEESE),
new Ingredient("SLSA", "Salsa", Type.SAUCE),
new Ingredient("SRCR", "Sour cream", Type.SAUCE));
new Ingredient("FLTO", "Flour tortilla", Type.WRAP),
new Ingredient("COTO", "Corn tortilla", Type.WRAP),
new Ingredient("GRBF", "Ground Beef", Type.PROTEIN),
new Ingredient("CARN", "Carnitas", Type.PROTEIN),
new Ingredient("TMTO", "Diced tomatoes", Type.VEGGIES),
new Ingredient("LETC", "Lettuce", Type.VEGGIES),
new Ingredient("CHED", "Ceddar", Type.CHEESE),
new Ingredient("JACK", "Monterrey Jack", Type.CHEESE),
new Ingredient("SLSA", "Salsa", Type.SAUCE),
new Ingredient("SRCR", "Sour cream", Type.SAUCE));

for (final Type type : Type.values()) {
model.addAttribute(type.toString().toLowerCase(), filterByType(ingredients, type));
Expand All @@ -48,19 +75,29 @@ public void addIngredientsToModel(final Model model) {

@GetMapping
public String showDesignForm(final Model model) {
model.addAttribute("design", new Taco());
final List<Ingredient> ingredients = new ArrayList<>();
this.ingredientRepository.findAll().forEach(ingredients::add);

final List<Type> types = CollectionUtils.arrayToList(Type.values());
for (final Type type : types) {
model.addAttribute(type.toString().toLowerCase(),
filterByType(ingredients, type));
}

return "design";
}

@PostMapping
public String processDesign(@Valid @ModelAttribute("design") final Taco design,
final Errors errors,
final Model model) {
final Errors errors,
@ModelAttribute final Order order) {
if (errors.hasErrors()) {
log.error("Errors found on processDesign()");
return "design";
}

final Taco saved = this.tacoRepository.save(design);

log.info("processing design '{}'", design);
return "redirect:/orders/current";
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package es.msanchez.spring.springinaction.dao;

import es.msanchez.spring.springinaction.entities.Ingredient;
import org.springframework.stereotype.Repository;

@Repository
public interface IngredientRepository {

Iterable<Ingredient> findAll();

Ingredient findOne(final String id);

Ingredient save(final Ingredient ingredient);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package es.msanchez.spring.springinaction.dao;

import es.msanchez.spring.springinaction.entities.Ingredient;
import es.msanchez.spring.springinaction.enums.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class JdbcIngredientRepository implements IngredientRepository {

private JdbcTemplate jdbcTemplate;

/**
* @param jdbcTemplate -
*/
@Autowired
public JdbcIngredientRepository(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

@Override
public Iterable<Ingredient> findAll() {
return this.jdbcTemplate.query("select id, name, type from Ingredient", this::mapRowToIngredient);
}

private Ingredient mapRowToIngredient(final ResultSet rs,
final int rowNum) throws SQLException {
return new Ingredient(rs.getString("id"),
rs.getString("name"),
Type.valueOf(rs.getString("type")));
}

@Override
public Ingredient findOne(final String id) {
return this.jdbcTemplate.queryForObject("select id, name, type from Ingredient where id = ?",
this::mapRowToIngredient, id);
}

@Override
public Ingredient save(final Ingredient ingredient) {
this.jdbcTemplate.update("insert into Ingredient (id, name, type) values (?, ?, ?)",
ingredient.getId(),
ingredient.getName(),
ingredient.getType().toString());
return ingredient;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package es.msanchez.spring.springinaction.dao;

import es.msanchez.spring.springinaction.entities.Ingredient;
import es.msanchez.spring.springinaction.entities.Taco;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementCreatorFactory;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.Date;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.LocalDate;
import java.util.Arrays;

@Repository
public class JdbcTacoRepository implements TacoRepository {

private final JdbcTemplate jdbc;

@Autowired
public JdbcTacoRepository(final JdbcTemplate jdbc) {
this.jdbc = jdbc;
}

@Override
public Taco save(final Taco taco) {
final long tacoId = this.saveTacoInfo(taco);
taco.setId(tacoId);
taco.getIngredients().forEach(ing -> this.saveIngredientToTaco(ing, tacoId));
return taco;
}

private void saveIngredientToTaco(final Ingredient ingredient,
final long tacoId) {
this.jdbc.update("insert into Taco_Ingredients (taco, ingredient) values (?, ?)",
tacoId, ingredient.getId());
}

private long saveTacoInfo(final Taco taco) {
taco.setCreatedAt(Date.valueOf(LocalDate.now()));
final PreparedStatementCreator psc = new PreparedStatementCreatorFactory(
"insert into Taco (name, createdAt) values (?,?)",
Types.VARCHAR, Types.TIMESTAMP
).newPreparedStatementCreator(Arrays.asList(taco.getName(),
new Timestamp(taco.getCreatedAt().getTime())));

final KeyHolder keyHolder = new GeneratedKeyHolder();
this.jdbc.update(psc, keyHolder);
return keyHolder.getKey().longValue();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package es.msanchez.spring.springinaction.dao;

import es.msanchez.spring.springinaction.entities.Order;

public interface OrderRepository {

public Order save(final Order order);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package es.msanchez.spring.springinaction.dao;

import es.msanchez.spring.springinaction.entities.Taco;

public interface TacoRepository {

public Taco save(final Taco taco);

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ public class Taco {
private String name;

@Size(min = 1, message = "You must select at least 1 ingredient")
private List<String> ingredients;
private List<Ingredient> ingredients;

}

This file was deleted.

This file was deleted.

26 changes: 26 additions & 0 deletions spring/spring-in-action/src/main/resources/data.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
DELETE FROM Taco_Order_Tacos;
DELETE FROM Taco_Ingredients;
DELETE FROM Taco;
DELETE FROM Taco_Order;
DELETE FROM Ingredient;

INSERT INTO Ingredient (id, name, type)
VALUES ("FLTO", "Flour Tortilla", "Wrap");
INSERT INTO Ingredient (id, name, type)
VALUES ("COTO", "Corn Tortilla", "Wrap");
INSERT INTO Ingredient (id, name, type)
VALUES ("GRBF", "Ground Beef", "Protein");
INSERT INTO Ingredient (id, name, type)
VALUES ("CARN", "Carnitas", "Protein");
INSERT INTO Ingredient (id, name, type)
VALUES ("TMTO", "Diced Tomatoes", "Veggies");
INSERT INTO Ingredient (id, name, type)
VALUES ("LETC", "Lettuce", "Veggies");
INSERT INTO Ingredient (id, name, type)
VALUES ("CHED", "Cheddar", "Cheese");
INSERT INTO Ingredient (id, name, type)
VALUES ("JACK", "Monterrey Jack", "Cheese");
INSERT INTO Ingredient (id, name, type)
VALUES ("SLSA", "Salsa", "Sauce");
INSERT INTO Ingredient (id, name, type)
VALUES ("SRCR", "Sour Cream", "Sauce");
23 changes: 23 additions & 0 deletions spring/spring-in-action/src/main/resources/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,26 @@ ALTER TABLE Taco_Ingredients

ALTER TABLE Taco_Ingredients
ADD FOREIGN KEY (ingredient) REFERENCES Ingredient(id);

CREATE TABLE IF NOT EXISTS Taco_Order (
id IDENTITY,
deliveryName VARCHAR(50) NOT NULL,
deliveryStreet VARCHAR(50) NOT NULL,
deliveryCity VARCHAR(50) NOT NULL,
deliveryState VARCHAR(50) NOT NULL,
deliveryZip VARCHAR(10) NOT NULL,
ccNumber VARCHAR(16) NOT NULL,
ccCVV VARCHAR(5) NOT NULL,
placedAt TIMESTAMP NOT NULL
);

CREATE TABLE IF NOT EXISTS Taco_Order_Tacos (
tacoOrder BIGINT NOT NULL,
taco BIGINT NOT NULL
);

ALTER TABLE Taco_Order_Tacos
ADD FOREIGN KEY (tacoOrder) REFERENCES Taco_Order(id);

ALTER TABLE Taco_Order_Tacos
ADD FOREIGN KEY (taco) REFERENCES Taco(id);

0 comments on commit b6f2ed3

Please sign in to comment.