diff --git a/.gitignore b/.gitignore
index a285bb3..3ef0a49 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,7 +20,7 @@
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
.idea/sonarlint-state.xml
-.idea/sonarlint
+/.idea/sonarlint/
# Gradle
.idea/**/gradle.xml
@@ -44,3 +44,5 @@ target/
build/
logs/
data/
+
+.idea/dataSources.xml
diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml
index fdc392f..b3e9cbd 100644
--- a/.idea/jarRepositories.xml
+++ b/.idea/jarRepositories.xml
@@ -16,5 +16,10 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
index 62269df..5d98256 100644
--- a/.idea/misc.xml
+++ b/.idea/misc.xml
@@ -1,6 +1,9 @@
+
+
+
diff --git a/build.gradle b/build.gradle
index fa0ea28..c8ee529 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,7 +1,7 @@
-
-
plugins {
- id 'java'
+ id 'war'
+ id "org.gretty" version "3.0.3"
+ id "io.freefair.lombok" version "5.3.0"
}
group 'ru.dimon.spring'
@@ -9,10 +9,35 @@ version '1.0-SNAPSHOT'
repositories {
mavenCentral()
+ jcenter()
+
}
+def springVersion = '5.2.10.RELEASE'
+def jettyVersion = '9.2.26.v20180806'
+
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
+
+ compile group: 'org.springframework', name: 'spring-webmvc', version: springVersion
+ compile group: 'org.eclipse.jetty', name: 'jetty-server', version: jettyVersion
+ compile group: 'org.eclipse.jetty', name: 'jetty-webapp', version: jettyVersion
+ compile group: 'org.thymeleaf', name: 'thymeleaf-spring5', version: '3.0.10.RELEASE'
+ compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.6'
+ compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.13.3'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.13.3'
+
+ compile group: 'org.hibernate', name: 'hibernate-core', version: '5.4.4.Final'
+ compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.22'
+ // https://mvnrepository.com/artifact/com.h2database/h2
+ compile group: 'com.h2database', name: 'h2', version: '1.4.200'
+ compile group: 'org.springframework.data', name: 'spring-data-jpa', version: '2.2.5.RELEASE'
+
}
+
+gretty {
+ httpPort = 8080
+ contextPath = '/'
+}
+
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index 62d4c05..490fda8 100644
Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradlew b/gradlew
index fbd7c51..2fe81a7 100644
--- a/gradlew
+++ b/gradlew
@@ -82,7 +82,6 @@ esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
@@ -130,7 +129,6 @@ fi
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
-
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
diff --git a/gradlew.bat b/gradlew.bat
index 5093609..62bd9b9 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -84,7 +84,6 @@ set CMD_LINE_ARGS=%*
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
diff --git a/lombok.config b/lombok.config
new file mode 100644
index 0000000..6aa51d7
--- /dev/null
+++ b/lombok.config
@@ -0,0 +1,2 @@
+# This file is generated by the 'io.freefair.lombok' Gradle plugin
+config.stopBubbling = true
diff --git a/src/main/java/lessonfour/jpa/AppConfig.java b/src/main/java/lessonfour/jpa/AppConfig.java
new file mode 100644
index 0000000..40e1cfc
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/AppConfig.java
@@ -0,0 +1,122 @@
+package lessonfour.jpa;
+
+import org.hibernate.jpa.HibernatePersistenceProvider;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
+import org.springframework.orm.jpa.JpaTransactionManager;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
+import org.springframework.transaction.annotation.EnableTransactionManagement;
+import org.springframework.web.servlet.config.annotation.EnableWebMvc;
+import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+import org.thymeleaf.spring5.SpringTemplateEngine;
+import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
+import org.thymeleaf.spring5.view.ThymeleafViewResolver;
+
+import javax.persistence.EntityManagerFactory;
+import java.util.Properties;
+
+@EnableWebMvc
+@Configuration
+@ComponentScan("lessonfour.jpa")
+@EnableJpaRepositories("lessonfour.jpa.repositories")
+@EnableTransactionManagement
+public class AppConfig implements WebMvcConfigurer {
+ @Override
+ public void addResourceHandlers(ResourceHandlerRegistry registry) {
+ registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
+ }
+
+ @Bean
+ public SpringResourceTemplateResolver templateResolver() {
+ SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
+ templateResolver.setPrefix("/WEB-INF/templates/");
+ templateResolver.setSuffix(".html");
+ return templateResolver;
+ }
+
+ @Bean
+ public SpringTemplateEngine templateEngine() {
+ SpringTemplateEngine templateEngine = new SpringTemplateEngine();
+ templateEngine.setTemplateResolver(templateResolver());
+ return templateEngine;
+ }
+
+ @Bean
+ public ThymeleafViewResolver thymeleafViewResolver() {
+ ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
+ thymeleafViewResolver.setTemplateEngine(templateEngine());
+ thymeleafViewResolver.setCharacterEncoding("UTF-8");
+ return thymeleafViewResolver;
+ }
+
+ @Bean(name="dataSource")
+ public DriverManagerDataSource getDataSource() {
+
+ DriverManagerDataSource dataSource = new DriverManagerDataSource();
+ dataSource.setUrl("jdbc:h2:./data/h2db");
+ dataSource.setUsername("root");
+ dataSource.setPassword("12345");
+ dataSource.setDriverClassName("org.h2.Driver");
+ return dataSource;
+ }
+
+ @Bean(name="entityManagerFactory")
+ public LocalContainerEntityManagerFactoryBean getEntityManager() {
+ // Создаем класса фабрики, реализующей интерфейс
+ // FactoryBean
+ LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
+
+ // Задаем источник подключения
+ factory.setDataSource(getDataSource());
+
+ // Задаем адаптер для конкретной реализации JPA,
+ // указывает, какая именно библиотека будет использоваться в качестве
+ // поставщика постоянства
+ factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
+
+ // Указание пакета, в котором будут находиться классы-сущности
+ factory.setPackagesToScan("lessonfour.jpa.model");
+
+ // Создание свойств для настройки Hibernate
+ Properties jpaProperties = new Properties();
+
+ // Указание диалекта конкретной базы данных
+ jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
+
+ // Указание максимальной глубины связи
+ jpaProperties.put("hibernate.max_fetch_depth", 3);
+
+ // Максимальное количество строк, возвращаемых за один запрос из БД
+ jpaProperties.put("hibernate.jdbc.fetch_size", 50);
+
+ // Максимальное количество запросов при использовании пакетных операций
+ jpaProperties.put("hibernate.jdbc.batch_size", 10);
+
+ // Включает логирование
+ jpaProperties.put("hibernate.show_sql", true);
+
+ jpaProperties.put("hibernate.hbm2ddl.auto", "update");
+ jpaProperties.put("hibernate.enable_lazy_load_no_trans", true);
+
+
+
+ factory.setJpaProperties(jpaProperties);
+ return factory;
+ }
+
+ @Bean(name = "transactionManager")
+ public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
+ // Создание менеджера транзакций
+ JpaTransactionManager tm = new JpaTransactionManager();
+ tm.setEntityManagerFactory(entityManagerFactory);
+ return tm;
+ }
+
+
+
+}
diff --git a/src/main/java/lessonfour/jpa/Launcher.java b/src/main/java/lessonfour/jpa/Launcher.java
new file mode 100644
index 0000000..3e6cff4
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/Launcher.java
@@ -0,0 +1,24 @@
+package lessonfour.jpa;
+
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.webapp.WebAppContext;
+
+import java.net.URL;
+import java.security.ProtectionDomain;
+
+public class Launcher {
+ public static void main(String[] args) throws Exception {
+ Server server = new Server(8189);
+
+ ProtectionDomain domain = Launcher.class.getProtectionDomain();
+ URL location = domain.getCodeSource().getLocation();
+
+ WebAppContext webAppContext = new WebAppContext();
+ webAppContext.setContextPath("/");
+ webAppContext.setWar(location.toExternalForm());
+
+ server.setHandler(webAppContext);
+ server.start();
+ server.join();
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/lessonfour/jpa/WebInitializer.java b/src/main/java/lessonfour/jpa/WebInitializer.java
new file mode 100644
index 0000000..077c7d7
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/WebInitializer.java
@@ -0,0 +1,36 @@
+package lessonfour.jpa;
+
+import javax.servlet.Filter;
+import org.springframework.web.filter.CharacterEncodingFilter;
+import org.springframework.web.filter.HiddenHttpMethodFilter;
+import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
+
+public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
+ @Override
+ protected Class>[] getRootConfigClasses() {
+ return null;
+ }
+
+ @Override
+ protected Class>[] getServletConfigClasses() {
+ return new Class[]{AppConfig.class};
+ }
+
+ protected String[] getServletMappings() {
+ return new String[]{"/"};
+ }
+
+ @Override
+ protected Filter[] getServletFilters() {
+ // Создание фильтра кодировки, который позволит работать с русскими
+ // символами
+ CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
+ characterEncodingFilter.setEncoding("UTF-8");
+ characterEncodingFilter.setForceEncoding(true);
+ // Создание фильтра, который добавляет поддержку HTTP-методов (например
+ // таких, как PUT), необходимых для REST API
+ HiddenHttpMethodFilter httpMethodFilter = new HiddenHttpMethodFilter();
+ return new Filter[]{characterEncodingFilter, httpMethodFilter};
+ }
+
+}
diff --git a/src/main/java/lessonfour/jpa/controllers/CustomersController.java b/src/main/java/lessonfour/jpa/controllers/CustomersController.java
new file mode 100644
index 0000000..997a088
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/controllers/CustomersController.java
@@ -0,0 +1,57 @@
+package lessonfour.jpa.controllers;
+
+import lessonfour.jpa.model.Customer;
+import lessonfour.jpa.services.CustomerService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+
+import java.util.List;
+
+@Controller
+@RequestMapping("customers")
+public class CustomersController {
+ @Autowired
+ CustomerService customerService;
+
+ @RequestMapping(value = "", method = RequestMethod.GET)
+ public String showAllCustomers(Model model) {
+ List customerList = customerService.getAllCustomers();
+ model.addAttribute("customers", customerList);
+ return "customers/all_customers";
+ }
+
+ @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
+ public String showInfoCustomerForm(@PathVariable long id, Model model) {
+ model.addAttribute("customer", customerService.get(id));
+ return "customers/info_customer";
+ }
+
+ @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
+ public String showEditCustomerForm(@PathVariable long id, Model model) {
+ model.addAttribute("customer", customerService.get(id));
+ return "customers/edit_customer_form";
+ }
+
+ @RequestMapping(value = "/edit", method = RequestMethod.POST)
+ public String editCustomer(@ModelAttribute Customer customer) {
+ customerService.update(customer);
+ return "redirect:/customers/";
+ }
+
+ @RequestMapping(value = "/add", method = RequestMethod.GET)
+ public String showAddCustomerForm(Model model) {
+ model.addAttribute("customer", new Customer());
+ return "customers/add_customer_form";
+ }
+
+ @RequestMapping(value = "/add", method = RequestMethod.POST)
+ public String addCustomer(@ModelAttribute Customer customer) {
+ customerService.add(customer);
+ return "redirect:/customers/";
+ }
+}
diff --git a/src/main/java/lessonfour/jpa/controllers/MainController.java b/src/main/java/lessonfour/jpa/controllers/MainController.java
new file mode 100644
index 0000000..8c0982a
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/controllers/MainController.java
@@ -0,0 +1,14 @@
+package lessonfour.jpa.controllers;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.*;
+
+@Controller
+public class MainController {
+
+ @RequestMapping(value = "/", method = RequestMethod.GET)
+ public String showHomePage() {
+ return "index";
+ }
+
+}
diff --git a/src/main/java/lessonfour/jpa/controllers/OrdersController.java b/src/main/java/lessonfour/jpa/controllers/OrdersController.java
new file mode 100644
index 0000000..9789aca
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/controllers/OrdersController.java
@@ -0,0 +1,32 @@
+package lessonfour.jpa.controllers;
+
+import lessonfour.jpa.model.Order;
+import lessonfour.jpa.services.OrdersService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+
+import java.util.List;
+
+@Controller
+@RequestMapping("orders")
+public class OrdersController {
+ @Autowired
+ OrdersService ordersService;
+
+ @RequestMapping(value = "", method = RequestMethod.GET)
+ public String showAllOrder(Model model) {
+ List orderList = ordersService.getAllOrders();
+ model.addAttribute("orders", orderList);
+ return "orders/all_orders";
+ }
+
+ @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
+ public String showInfoOrderForm(@PathVariable long id, Model model) {
+ model.addAttribute("order", ordersService.get(id));
+ return "orders/info_order";
+ }
+}
diff --git a/src/main/java/lessonfour/jpa/controllers/ProductsController.java b/src/main/java/lessonfour/jpa/controllers/ProductsController.java
new file mode 100644
index 0000000..74fb73d
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/controllers/ProductsController.java
@@ -0,0 +1,107 @@
+package lessonfour.jpa.controllers;
+
+import lessonfour.jpa.model.Product;
+import lessonfour.jpa.repositories.specifications.SpecificationImpl;
+import lessonfour.jpa.repositories.specifications.SpecificationsBuilder;
+import lessonfour.jpa.services.ProductsService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Sort;
+import org.springframework.data.jpa.domain.Specification;
+import org.springframework.stereotype.Controller;
+import org.springframework.ui.Model;
+import org.springframework.web.bind.annotation.*;
+
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+@Controller
+@RequestMapping("products")
+public class ProductsController {
+
+ @Autowired
+ ProductsService productsService;
+
+ @RequestMapping(value = "", method = RequestMethod.GET)
+ public String showAllProducts(Model model,
+ @RequestParam(name = "p", required = false, defaultValue = "1") Integer pageNumber,
+ @RequestParam(name = "min_cost", required = false) Float minCost,
+ @RequestParam(name = "max_cost", required = false) Float maxCost,
+ @RequestParam(name = "order", required = false) String order) {
+
+ SpecificationsBuilder productSpecificationsBuilder = new SpecificationsBuilder<>();
+ if(minCost != null) {
+ productSpecificationsBuilder.with("cost", ">=", minCost, false);
+ }
+ if (maxCost != null) {
+ productSpecificationsBuilder.with("cost", "<=", maxCost, false);
+ }
+ Specification spec = productSpecificationsBuilder.build();
+// Sort sort = Sort.unsorted();
+// if(sortByCost != null) {
+// sort = sortByCost.equalsIgnoreCase("desc") ?
+// sort.and(Sort.by("cost").descending()):
+// sort.and(Sort.by("cost").ascending());
+// }
+ Sort sort = Sort.unsorted();
+ Pattern pattern = Pattern.compile("(\\w+?)(:)(\\w+?),");
+ Matcher matcher = pattern.matcher(order + ",");
+ while (matcher.find()) {
+ Sort.Direction direction = matcher.group(3).equalsIgnoreCase("desc") ?
+ Sort.Direction.DESC:
+ Sort.Direction.ASC;
+ sort = sort.and(Sort.by(direction, matcher.group(1)));
+ }
+
+ List productList = productsService.getAllProducts(spec, pageNumber, sort);
+
+ model.addAttribute("products", productList);
+ return "products/all_products";
+ }
+
+ @RequestMapping(value = "/repo", method = RequestMethod.GET)
+ public String showAllProductsRepo(Model model,
+ @RequestParam(name = "p", required = false, defaultValue = "1") Integer pageNumber,
+ @RequestParam(name = "min_cost", required = false) Float minCost,
+ @RequestParam(name = "max_cost", required = false) Float maxCost,
+ @RequestParam(name = "sortByCost", required = false, defaultValue = "asc") String sortByCost) {
+
+ List productList = productsService.getAllProducts(minCost, maxCost, pageNumber, sortByCost);
+ model.addAttribute("products", productList);
+ return "products/all_products";
+ }
+
+ @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
+ public String showEditProductForm(@PathVariable long id, Model model) {
+ model.addAttribute("product", productsService.get(id));
+ return "products/edit_product_form";
+ }
+
+ @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
+ public String showInfoProductForm(@PathVariable long id, Model model) {
+ model.addAttribute("product", productsService.get(id));
+ return "products/info_product";
+ }
+
+ @RequestMapping(value = "/edit", method = RequestMethod.POST)
+ public String editProduct(@ModelAttribute Product product) {
+ productsService.update(product);
+ return "redirect:/products/";
+ }
+
+ @RequestMapping(value = "/add", method = RequestMethod.GET)
+ public String showAddProductForm(Model model) {
+ model.addAttribute("product", new Product());
+ return "products/add_product_form";
+ }
+
+ @RequestMapping(value = "/add", method = RequestMethod.POST)
+ public String addProduct(@ModelAttribute Product product) {
+ productsService.add(product);
+ return "redirect:/products/";
+ }
+
+
+
+
+}
diff --git a/src/main/java/lessonfour/jpa/model/Customer.java b/src/main/java/lessonfour/jpa/model/Customer.java
new file mode 100644
index 0000000..b1684df
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/model/Customer.java
@@ -0,0 +1,43 @@
+package lessonfour.jpa.model;
+
+import javax.persistence.*;
+import java.util.ArrayList;
+import java.util.List;
+
+@Entity
+@Table(name = "customers")
+public class Customer {
+ @Id
+ @Column(name = "id")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ @Column(name = "first_name")
+ private String first_name;
+
+ @OneToMany(mappedBy = "customer", cascade = {CascadeType.REMOVE})
+ List orders = new ArrayList<>();
+
+ public Long getId() {
+ return id;
+ }
+
+ public String getFirst_name() {
+ return first_name;
+ }
+
+ public void setFirst_name(String first_name) {
+ this.first_name = first_name;
+ }
+
+ public List getOrders() {
+ return orders;
+ }
+
+ public void setOrders(List orders) {
+ this.orders = orders;
+ }
+
+
+
+}
diff --git a/src/main/java/lessonfour/jpa/model/Order.java b/src/main/java/lessonfour/jpa/model/Order.java
new file mode 100644
index 0000000..2d9d082
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/model/Order.java
@@ -0,0 +1,53 @@
+package lessonfour.jpa.model;
+
+import javax.persistence.*;
+import java.util.Date;
+import java.util.List;
+
+
+@Entity
+@Table(name = "orders")
+public class Order {
+ @Id
+ @Column(name = "id")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ @Column(name = "date", nullable = false)
+ private Date date;
+
+ @ManyToOne
+ @JoinColumn(name = "customer_id", nullable = false)
+ private Customer customer;
+
+ @OneToMany(mappedBy="order", fetch = FetchType.LAZY)
+ private List orderProducts;
+
+ public Long getId() {
+ return id;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ public Customer getCustomer() {
+ return customer;
+ }
+
+ public void setCustomer(Customer customer) {
+ this.customer = customer;
+ }
+
+ public List getOrderProducts() {
+ return orderProducts;
+ }
+
+ public void setOrderProducts(List orderProducts) {
+ this.orderProducts = orderProducts;
+ }
+}
diff --git a/src/main/java/lessonfour/jpa/model/OrderProduct.java b/src/main/java/lessonfour/jpa/model/OrderProduct.java
new file mode 100644
index 0000000..c8d3bef
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/model/OrderProduct.java
@@ -0,0 +1,67 @@
+package lessonfour.jpa.model;
+
+import javax.persistence.*;
+
+@Entity
+@Table(name = "order_products")
+public class OrderProduct {
+
+ @Id
+ @Column(name = "id")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ @ManyToOne
+ @JoinColumn(name = "order_id", nullable = false)
+ private Order order;
+
+ @OneToOne
+ @JoinColumn(name = "product_id")
+ private Product product;
+
+ @Column(name = "count")
+ private int count;
+
+ @Column(name = "cost")
+ private int cost;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Order getOrder() {
+ return order;
+ }
+
+ public void setOrder(Order order) {
+ this.order = order;
+ }
+
+ public Product getProduct() {
+ return product;
+ }
+
+ public void setProduct(Product product) {
+ this.product = product;
+ }
+
+ public int getCount() {
+ return count;
+ }
+
+ public void setCount(int count) {
+ this.count = count;
+ }
+
+ public int getCost() {
+ return cost;
+ }
+
+ public void setCost(int cost) {
+ this.cost = cost;
+ }
+}
diff --git a/src/main/java/lessonfour/jpa/model/Product.java b/src/main/java/lessonfour/jpa/model/Product.java
new file mode 100644
index 0000000..9a926e5
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/model/Product.java
@@ -0,0 +1,76 @@
+package lessonfour.jpa.model;
+
+import javax.persistence.*;
+import java.util.List;
+import java.util.Objects;
+
+@Entity
+@Table(name = "products")
+public class Product {
+ @Id
+ @Column(name = "id")
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ @Column(name = "title")
+ private String title;
+
+ @Column(name = "cost")
+ private float cost;
+
+ @ManyToMany
+ @JoinTable(
+ name = "order_products",
+ joinColumns = @JoinColumn(name = "product_id"),
+ inverseJoinColumns = @JoinColumn(name = "order_id")
+ )
+ private List orders;
+
+ public Product() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public float getCost() {
+ return cost;
+ }
+
+ public void setCost(float cost) {
+ this.cost = cost;
+ }
+
+ public Product(Long id, String title, float cost) {
+ this.id = id;
+ this.title = title;
+ this.cost = cost;
+ }
+
+ public List getOrders() {
+ return orders;
+ }
+ @Override
+ public boolean equals(Object o) { if ( this == o ) return true;
+ if ( o == null || getClass() != o.getClass() ) return false;
+ Product product = (Product) o;
+ return Objects.equals(id, product.id);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id);
+ }
+}
diff --git a/src/main/java/lessonfour/jpa/repositories/CustomerRepository.java b/src/main/java/lessonfour/jpa/repositories/CustomerRepository.java
new file mode 100644
index 0000000..04bcc4c
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/repositories/CustomerRepository.java
@@ -0,0 +1,10 @@
+package lessonfour.jpa.repositories;
+
+import lessonfour.jpa.model.Customer;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface CustomerRepository extends JpaRepository {
+
+}
diff --git a/src/main/java/lessonfour/jpa/repositories/OrderRepository.java b/src/main/java/lessonfour/jpa/repositories/OrderRepository.java
new file mode 100644
index 0000000..803c84b
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/repositories/OrderRepository.java
@@ -0,0 +1,10 @@
+package lessonfour.jpa.repositories;
+
+import lessonfour.jpa.model.Order;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface OrderRepository extends JpaRepository {
+
+}
diff --git a/src/main/java/lessonfour/jpa/repositories/ProductRepository.java b/src/main/java/lessonfour/jpa/repositories/ProductRepository.java
new file mode 100644
index 0000000..3453691
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/repositories/ProductRepository.java
@@ -0,0 +1,17 @@
+package lessonfour.jpa.repositories;
+
+import lessonfour.jpa.model.Product;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
+import org.springframework.data.repository.PagingAndSortingRepository;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository
+public interface ProductRepository extends JpaRepository, PagingAndSortingRepository, JpaSpecificationExecutor {
+ List findByCostGreaterThan(Float minCost, Pageable page);
+ List findByCostLessThan(Float maxCost, Pageable page);
+ List findByCostBetween(Float minCost, Float maxCost, Pageable page);
+}
diff --git a/src/main/java/lessonfour/jpa/repositories/specifications/SearchCriteria.java b/src/main/java/lessonfour/jpa/repositories/specifications/SearchCriteria.java
new file mode 100644
index 0000000..07e24ff
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/repositories/specifications/SearchCriteria.java
@@ -0,0 +1,13 @@
+package lessonfour.jpa.repositories.specifications;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+@Data
+@AllArgsConstructor
+public class SearchCriteria {
+ private String key;
+ private String operation;
+ private Object value;
+ private boolean orPredicate;
+}
diff --git a/src/main/java/lessonfour/jpa/repositories/specifications/SpecificationImpl.java b/src/main/java/lessonfour/jpa/repositories/specifications/SpecificationImpl.java
new file mode 100644
index 0000000..ae02b19
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/repositories/specifications/SpecificationImpl.java
@@ -0,0 +1,41 @@
+package lessonfour.jpa.repositories.specifications;
+
+import org.springframework.data.jpa.domain.Specification;
+
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Predicate;
+import javax.persistence.criteria.Root;
+
+public class SpecificationImpl implements Specification {
+ private SearchCriteria criteria;
+
+ SpecificationImpl(SearchCriteria criteria) {
+ this.criteria = criteria;
+ }
+
+ @Override
+ public Predicate toPredicate(Root root, CriteriaQuery> query, CriteriaBuilder criteriaBuilder) {
+ if (criteria.getOperation().equalsIgnoreCase(">=")) {
+ return criteriaBuilder.greaterThanOrEqualTo(
+ root.get(criteria.getKey()), criteria.getValue().toString());
+ }
+ else if (criteria.getOperation().equalsIgnoreCase("<=")) {
+ return criteriaBuilder.lessThanOrEqualTo(
+ root.get(criteria.getKey()), criteria.getValue().toString());
+ }
+ else if (criteria.getOperation().equalsIgnoreCase("=")) {
+ return criteriaBuilder.equal(
+ root.get(criteria.getKey()), criteria.getValue().toString());
+ }
+ else if (criteria.getOperation().equalsIgnoreCase(":")) {
+ if (root.get(criteria.getKey()).getJavaType() == String.class) {
+ return criteriaBuilder.like(
+ root.get(criteria.getKey()), "%" + criteria.getValue() + "%");
+ } else {
+ return criteriaBuilder.equal(root.get(criteria.getKey()), criteria.getValue());
+ }
+ }
+ return null;
+ }
+}
diff --git a/src/main/java/lessonfour/jpa/repositories/specifications/SpecificationsBuilder.java b/src/main/java/lessonfour/jpa/repositories/specifications/SpecificationsBuilder.java
new file mode 100644
index 0000000..ecb1591
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/repositories/specifications/SpecificationsBuilder.java
@@ -0,0 +1,40 @@
+package lessonfour.jpa.repositories.specifications;
+
+import org.springframework.data.jpa.domain.Specification;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class SpecificationsBuilder {
+ private final List params;
+
+ public SpecificationsBuilder() {
+ this.params = new ArrayList<>();
+ }
+
+ public SpecificationsBuilder with(String key, String operation, Object value, boolean isOrPredicate) {
+ params.add(new SearchCriteria(key, operation, value, isOrPredicate));
+ return this;
+ }
+
+ public Specification build() {
+ if (params.size() == 0) {
+ return null;
+ }
+
+ List specs = params.stream()
+ .map(SpecificationImpl::new)
+ .collect(Collectors.toList());
+
+ Specification result = specs.get(0);
+
+ for (int i = 1; i < params.size(); i++) {
+ result = params.get(i).isOrPredicate()
+ ? Specification.where(result).or(specs.get(i))
+ : Specification.where(result).and(specs.get(i));
+ }
+ return result;
+ }
+}
+
diff --git a/src/main/java/lessonfour/jpa/services/CustomerService.java b/src/main/java/lessonfour/jpa/services/CustomerService.java
new file mode 100644
index 0000000..170f433
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/services/CustomerService.java
@@ -0,0 +1,33 @@
+package lessonfour.jpa.services;
+
+import lessonfour.jpa.model.Customer;
+import lessonfour.jpa.repositories.CustomerRepository;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import javax.transaction.Transactional;
+import java.util.List;
+
+@Service
+@Transactional
+public class CustomerService {
+
+ @Autowired
+ private CustomerRepository customerRepository;
+
+ public List getAllCustomers() {
+ return customerRepository.findAll();
+ }
+
+ public Customer get(long id) {
+ return customerRepository.getOne(id);
+ }
+
+ public Customer add(Customer customer) {
+ return customerRepository.save(customer);
+ }
+
+ public Customer update(Customer customer) {
+ return customerRepository.save(customer);
+ }
+}
diff --git a/src/main/java/lessonfour/jpa/services/OrdersService.java b/src/main/java/lessonfour/jpa/services/OrdersService.java
new file mode 100644
index 0000000..d48c4d2
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/services/OrdersService.java
@@ -0,0 +1,24 @@
+package lessonfour.jpa.services;
+
+import lessonfour.jpa.model.Order;
+import lessonfour.jpa.repositories.OrderRepository;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import javax.transaction.Transactional;
+import java.util.List;
+
+@Service
+@Transactional
+public class OrdersService {
+ @Autowired
+ private OrderRepository orderRepository;
+
+ public Order get(long id) {
+ return orderRepository.getOne(id);
+ }
+
+ public List getAllOrders() {
+ return orderRepository.findAll();
+ }
+}
diff --git a/src/main/java/lessonfour/jpa/services/ProductsService.java b/src/main/java/lessonfour/jpa/services/ProductsService.java
new file mode 100644
index 0000000..a716c26
--- /dev/null
+++ b/src/main/java/lessonfour/jpa/services/ProductsService.java
@@ -0,0 +1,72 @@
+package lessonfour.jpa.services;
+
+import lessonfour.jpa.model.Product;
+import lessonfour.jpa.repositories.ProductRepository;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Sort;
+import org.springframework.data.jpa.domain.Specification;
+import org.springframework.stereotype.Service;
+
+import javax.transaction.Transactional;
+import java.awt.print.Pageable;
+import java.util.List;
+
+@Service
+@Transactional
+public class ProductsService {
+
+ @Autowired
+ private ProductRepository productRepository;
+
+ public List getAllProducts() {
+ return productRepository.findAll();
+ }
+
+ public List getAllProducts(Float minCost, Float maxCost, Integer pageNumber, String sortByCost) {
+ if(!sortByCost.equals("asc") && !sortByCost.equals("desc")) {
+ sortByCost = "asc";
+ }
+ if (pageNumber < 1) {
+ pageNumber = 1;
+ }
+ Sort sort = Sort.by("cost");
+ if (sortByCost.equals("desc")) {
+ sort = sort.descending();
+ }
+ PageRequest pageRequest = PageRequest.of(pageNumber - 1, 5, sort);
+
+ if(minCost != null && maxCost != null) {
+ return productRepository.findByCostBetween(minCost, maxCost, pageRequest);
+ }else if(minCost != null) {
+ return productRepository.findByCostGreaterThan(minCost, pageRequest);
+ }else if(maxCost != null) {
+ return productRepository.findByCostLessThan(maxCost, pageRequest);
+ }else{
+ return productRepository.findAll(pageRequest).toList();
+ }
+ }
+
+ public List getAllProducts(Specification spec, Integer pageNumber, Sort sort) {
+ if (pageNumber < 1) {
+ pageNumber = 1;
+ }
+ PageRequest pageRequest = PageRequest.of(pageNumber - 1, 5, sort);
+ return productRepository.findAll(spec, pageRequest).toList();
+ }
+
+
+ public Product get(long id) {
+ return productRepository.getOne(id);
+ }
+
+ public Product add(Product product) {
+ return productRepository.save(product);
+ }
+
+ public Product update(Product product) {
+ return productRepository.save(product);
+ }
+
+}
diff --git a/src/main/resources/hibernate.h2.cfg.xml b/src/main/resources/hibernate.h2.cfg.xml
new file mode 100644
index 0000000..de8211b
--- /dev/null
+++ b/src/main/resources/hibernate.h2.cfg.xml
@@ -0,0 +1,23 @@
+
+
+
+
+ org.h2.Driver
+ jdbc:h2:./data/h2db
+ root
+ 12345
+ 8
+ org.hibernate.dialect.H2Dialect
+ true
+ thread
+ update
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/main/resources/hibernate.mysql.cfg.xml b/src/main/resources/hibernate.mysql.cfg.xml
new file mode 100644
index 0000000..c996229
--- /dev/null
+++ b/src/main/resources/hibernate.mysql.cfg.xml
@@ -0,0 +1,23 @@
+
+
+
+
+ com.mysql.cj.jdbc.Driver
+ jdbc:mysql://localserver:3306/shop?serverTimezone=UTC
+ root
+ 12345
+ 8
+ org.hibernate.dialect.MySQL8Dialect
+ true
+ thread
+ update
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/main/resources/log4j2.xml b/src/main/resources/log4j2.xml
new file mode 100644
index 0000000..78aa60c
--- /dev/null
+++ b/src/main/resources/log4j2.xml
@@ -0,0 +1,25 @@
+
+
+
+ logs
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/templates/customers/add_customer_form.html b/src/main/webapp/WEB-INF/templates/customers/add_customer_form.html
new file mode 100644
index 0000000..40c54ed
--- /dev/null
+++ b/src/main/webapp/WEB-INF/templates/customers/add_customer_form.html
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+ Spring MVC GeekApp
+
+
+
+ Add new customer
+
+
+
+
+ to main page
+
+
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/templates/customers/all_customers.html b/src/main/webapp/WEB-INF/templates/customers/all_customers.html
new file mode 100644
index 0000000..7e0c71e
--- /dev/null
+++ b/src/main/webapp/WEB-INF/templates/customers/all_customers.html
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+ Spring MVC GeekApp
+
+
+
+ customers list:
+
+
+
+ Id
+ Name
+ ...
+ ...
+
+
+
+
+
+
+ edit
+ info
+
+
+
+
+ add new customer
+
+ to main page
+
+
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/templates/customers/edit_customer_form.html b/src/main/webapp/WEB-INF/templates/customers/edit_customer_form.html
new file mode 100644
index 0000000..a6a5ae8
--- /dev/null
+++ b/src/main/webapp/WEB-INF/templates/customers/edit_customer_form.html
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+ Spring MVC GeekApp
+
+
+
+ Edit customer
+
+
+ to main page
+
+
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/templates/customers/info_customer.html b/src/main/webapp/WEB-INF/templates/customers/info_customer.html
new file mode 100644
index 0000000..0662699
--- /dev/null
+++ b/src/main/webapp/WEB-INF/templates/customers/info_customer.html
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+ Spring MVC GeekApp
+
+
+
+Info customer
+
+
Id:
+
Name:
+
+
Orders:
+
+
+
+ Id
+ date
+ ...
+
+
+
+
+
+
+ info
+
+
+
+
+
+to main page
+
+
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/templates/index.html b/src/main/webapp/WEB-INF/templates/index.html
new file mode 100644
index 0000000..fd0bb3c
--- /dev/null
+++ b/src/main/webapp/WEB-INF/templates/index.html
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+ Spring MVC GeekApp
+
+
+
+ WEB: Spring MVC GeekApp
+ Site map
+ Products list
+
+ Customers list
+
+ Orders list
+
+
+
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/templates/orders/all_orders.html b/src/main/webapp/WEB-INF/templates/orders/all_orders.html
new file mode 100644
index 0000000..203b264
--- /dev/null
+++ b/src/main/webapp/WEB-INF/templates/orders/all_orders.html
@@ -0,0 +1,33 @@
+
+
+
+
+
+
+ Spring MVC GeekApp
+
+
+
+ Orders list:
+
+
+
+ Id
+ Customer
+ Date
+ ...
+
+
+
+
+
+
+
+ info
+
+
+
+
+ to main page
+
+
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/templates/orders/info_order.html b/src/main/webapp/WEB-INF/templates/orders/info_order.html
new file mode 100644
index 0000000..0b6d535
--- /dev/null
+++ b/src/main/webapp/WEB-INF/templates/orders/info_order.html
@@ -0,0 +1,38 @@
+
+
+
+
+
+
+ Spring MVC GeekApp
+
+
+
+Info order
+
+
Id:
+
Date:
+
Customer:
+
+
Products:
+
+
+
+ product
+ count
+ cost
+
+
+
+
+
+
+
+
+
+
+
+
+to main page
+
+
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/templates/products/add_product_form.html b/src/main/webapp/WEB-INF/templates/products/add_product_form.html
new file mode 100644
index 0000000..1e23789
--- /dev/null
+++ b/src/main/webapp/WEB-INF/templates/products/add_product_form.html
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+ Spring MVC GeekApp
+
+
+
+ Add new product
+
+
+
+
+ to main page
+
+
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/templates/products/all_products.html b/src/main/webapp/WEB-INF/templates/products/all_products.html
new file mode 100644
index 0000000..a4abee1
--- /dev/null
+++ b/src/main/webapp/WEB-INF/templates/products/all_products.html
@@ -0,0 +1,36 @@
+
+
+
+
+
+
+ Spring MVC GeekApp
+
+
+
+ Products list:
+
+
+
+ Id
+ Title
+ Cost
+ ...
+ ...
+
+
+
+
+
+
+
+ edit
+ info
+
+
+
+ add new product
+
+ to main page
+
+
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/templates/products/edit_product_form.html b/src/main/webapp/WEB-INF/templates/products/edit_product_form.html
new file mode 100644
index 0000000..18d2913
--- /dev/null
+++ b/src/main/webapp/WEB-INF/templates/products/edit_product_form.html
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+ Spring MVC GeekApp
+
+
+
+ Edit product
+
+
+ to main page
+
+
\ No newline at end of file
diff --git a/src/main/webapp/WEB-INF/templates/products/info_product.html b/src/main/webapp/WEB-INF/templates/products/info_product.html
new file mode 100644
index 0000000..2c8ac0d
--- /dev/null
+++ b/src/main/webapp/WEB-INF/templates/products/info_product.html
@@ -0,0 +1,40 @@
+
+
+
+
+
+
+ Spring MVC GeekApp
+
+
+
+Info product
+
+
Id:
+
Title:
+
Cost:
+
+
+
Orders:
+
+
+
+ Id
+ date
+ ...
+
+
+
+
+
+
+ info
+
+
+
+
+
+
+to main page
+
+
\ No newline at end of file