Skip to content

Commit

Permalink
try string converter
Browse files Browse the repository at this point in the history
  • Loading branch information
AnuchitO committed Mar 22, 2024
1 parent ca3045b commit f327928
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.*;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
Expand Down Expand Up @@ -45,12 +46,9 @@ public class Promotion {
@Column(name = "applicable_to", nullable = false)
private String applicableTo;

@ElementCollection
@CollectionTable(
name = "promotion_product_skus",
joinColumns = @JoinColumn(name = "promotion_id"))
@Column(name = "product_sku")
private List<String> productSkus;
@Convert(converter = StringListConverter.class)
@Column(name = "product_skus")
private List<String> productSkus;;

@Column(name = "min_quantity")
private Integer minQuantity;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

public record PromotionResponse(
Long promotionId,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.kampus.kbazaar.promotion;

import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

import java.util.Arrays;
import java.util.List;

import static java.util.Collections.emptyList;

@Converter
public class StringListConverter implements AttributeConverter<List<String>, String> {
private static final String SPLIT_CHAR = ",";

@Override
public String convertToDatabaseColumn(List<String> values) {
return values != null ? String.format("{%s}", String.join(SPLIT_CHAR, values)) : "";
}

@Override
public List<String> convertToEntityAttribute(String value) {
if (value == null) {
return emptyList();
}

String vs = value.replace("{", "").replace("}", "");
return Arrays.asList(vs.split(SPLIT_CHAR));
}
}
4 changes: 1 addition & 3 deletions kbazaar/src/main/resources/sql/schema/product.sql
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,5 @@ CREATE TABLE IF NOT EXISTS product (
name VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
quantity INT NOT NULL,
sku VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
sku VARCHAR(255) NOT NULL UNIQUE
);

0 comments on commit f327928

Please sign in to comment.