Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Product update product entity #50

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

Expand Down Expand Up @@ -56,6 +56,7 @@
<logstash-logback-encoder.version>7.3</logstash-logback-encoder.version>
<spring-boot-maven-plugin.version>3.0.0</spring-boot-maven-plugin.version>
<postgresql.version>42.6.0</postgresql.version>
<liquibase.verson>4.23.0</liquibase.verson>
</properties>
<dependencies>

Expand Down Expand Up @@ -192,8 +193,14 @@
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>${liquibase.verson}</version>
</dependency>
</dependencies>


<build>
<plugins>
<plugin>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.zufar.onlinestore.product;

import com.zufar.onlinestore.product.dto.ProductInfoDto;

import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collection;

@Service
public class ProductsSumCalculator {

public BigDecimal calculate(final Collection<ProductInfoDto> products) {
return products.stream()
.map(productInfo -> productInfo.priceDetails().price())
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.zufar.onlinestore.product.converter;

import com.zufar.onlinestore.product.dto.PriceDetailsDto;
import com.zufar.onlinestore.product.dto.ProductInfoDto;
import com.zufar.onlinestore.product.entity.ProductInfo;
import org.springframework.stereotype.Component;

@Component
public class ProductInfoDtoConverter {

public ProductInfoDto convertToDto(final ProductInfo entity) {
PriceDetailsDto priceDetailsDto = new PriceDetailsDto(entity.getPrice(), entity.getCurrency());

return new ProductInfoDto(
entity.getId(),
entity.getDescription(),
entity.getName(),
priceDetailsDto
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.zufar.onlinestore.product.dto;

import jakarta.validation.constraints.DecimalMin;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;

import java.math.BigDecimal;

public record PriceDetailsDto(
@NotNull(message = "Price is mandatory")
@DecimalMin(value = "0.0", message = "Price minimum value should be more than 0.0")
BigDecimal price,

@NotBlank(message = "Currency is mandatory")
@Size(max = 55, message = "Currency length must be less than 55 characters")
String currency
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.zufar.onlinestore.product.dto;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;

import java.util.UUID;

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Как предлагал Женя, можем использовать функционал новой java, а именно record , что бы не писать множество ненужного кода

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Также на рекорды можно будет перенести валидацию

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Но если все таки будет принято рещение не использовать record, то тут нужно убрать лишний код, геттеры, сеттеры, хеш код и т.д . Поскольку стоит аннотация Data и благодаря ей Lombok создаст все это дело сам

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Как предлагал Женя, можем использовать функционал новой java, а именно record , что бы не писать множество ненужного кода

Согласен, давайте с record

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Здесь 100% record, но я так не делал для того чтобы это добавить в отдельной таске - для атомарности

public record ProductInfoDto(
@NotNull(message = "Id is mandatory")
UUID id,

@NotBlank(message = "Name is mandatory")
@Size(max = 100, message = "Name length must be less than 100 characters")
String name,

@NotBlank(message = "Description is mandatory")
@Size(max = 1000, message = "Description length must be less than 1000 characters")
String description,

@NotNull(message = "Price details is mandatory")
PriceDetailsDto priceDetails
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package com.zufar.onlinestore.product.endpoint;

import com.zufar.onlinestore.product.converter.ProductInfoDtoConverter;
import com.zufar.onlinestore.product.dto.ProductInfoDto;
import com.zufar.onlinestore.product.entity.ProductInfo;
import com.zufar.onlinestore.product.repository.ProductInfoRepository;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Optional;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequiredArgsConstructor
@Validated
@RequestMapping(value = "/api/products")
public class ProductsEndpoint {
private final ProductInfoRepository productInfoRepository;
private final ProductInfoDtoConverter productInfoDtoConverter;

@GetMapping("/{id}")
@ResponseBody
public ResponseEntity<ProductInfoDto> getProductInfoById(@PathVariable("id") final String id) {
log.info("Received request to get the ProductInfo with id - {}.", id);
Optional<ProductInfo> ProductInfo = productInfoRepository.findById(Integer.parseInt(id));
if (ProductInfo.isEmpty()) {
log.info("the ProductInfo with id - {} is absent.", id);
return ResponseEntity.notFound()
.build();
}
ProductInfoDto ProductInfoDto = productInfoDtoConverter.convertToDto(ProductInfo.get());
log.info("the ProductInfo with id - {} was retrieved - {}.", id, ProductInfoDto);
return ResponseEntity.ok()
.body(ProductInfoDto);
}

@GetMapping
@ResponseBody
public ResponseEntity<Collection<ProductInfoDto>> getAllProducts() {
log.info("Received request to get all ProductInfos");
Collection<ProductInfo> productInfoCollection = productInfoRepository.findAll();
if (productInfoCollection.isEmpty()) {
log.info("All ProductInfos are absent.");
return ResponseEntity.notFound()
.build();
}
Collection<ProductInfoDto> ProductInfos = productInfoCollection.stream()
.map(productInfoDtoConverter::convertToDto)
.toList();

log.info("All ProductInfos were retrieved - {}.", ProductInfos);
return ResponseEntity.ok()
.body(ProductInfos);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package com.zufar.onlinestore.product.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;

import java.math.BigDecimal;
import java.util.Objects;
import java.util.UUID;

@Getter
@Setter
@Entity
@Table(name = "product")
public class ProductInfo {

@Id
@GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут вот ребята подскажите, есть вариант в самой сущности поле сделать как String. Hibernate умеет конвертировать сразу все это дело, как вариант не нужно будет UUID приводить к String, не знаю насколько это уместно будет

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кажется должно быть

@id
@column(nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE)


@Column(name = "name", nullable = false)
private String name;

@Column(name = "description", nullable = false)
private String description;

@Column(name = "price", nullable = false)
private BigDecimal price;

@Column(name = "currency", nullable = false)
private String currency;

@Column(name = "quantity", nullable = false)
private Integer quantity;

@Column(name = "active", nullable = false)
private Boolean active;

public ProductInfo() {
}

@Override
public boolean equals(Object object) {
if (this == object)
return true;
if (object == null || getClass() != object.getClass())
return false;
ProductInfo that = (ProductInfo) object;
return active == that.active &&
Objects.equals(id, that.id) &&
Objects.equals(name, that.name) &&
Objects.equals(description, that.description) &&
Objects.equals(price, that.price) &&
Objects.equals(currency, that.currency) &&
Objects.equals(quantity, that.quantity);
}

@Override
public int hashCode() {
return Objects.hash(id, name, description, price, currency, quantity, active);
}

@Override
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove

public String toString() {
return "ProductInfo {" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", price=" + price +
", currency='" + currency + '\'' +
", quantity=" + quantity +
", active=" + active +
'}';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.zufar.onlinestore.product.repository;

import com.zufar.onlinestore.product.entity.ProductInfo;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ProductInfoRepository extends JpaRepository<ProductInfo, Integer> {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
CREATE TABLE IF NOT EXISTS product
(
id UUID,
name VARCHAR(64) NOT NULL,
description TEXT,
price DECIMAL NOT NULL CHECK (price > 0),
currency VARCHAR NOT NULL,
quantity INT NOT NULL CHECK (quantity >= 0),
active BOOLEAN NOT NULL,
PRIMARY KEY (id)
);
2 changes: 2 additions & 0 deletions src/main/resources/db/db.changelog-master.yaml
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
databaseChangeLog:
- include:
file: 19.07.2023.product-table-was-created.sql
Loading