Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@Component
class DataInitializer(
val productRepo: ProductRepository,
val priceRepo: ProductPriceRepository,
val priceHistoryRepo: PriceHistoryRepository
) : ApplicationListener<ContextStartedEvent> {
override fun onApplicationEvent(event: ContextStartedEvent) {
// clean up
productRepo.deleteAll()
priceRepo.deleteAll()
priceHistoryRepo.deleteAll()
val p1 = productRepo.save(Product(sku = "123", name = "Toy Horse"))
val p2 = productRepo.save(Product(sku = "456", name = "Real Horse"))
val h1 = PriceHistory(sku = p1.sku)
val h2 = PriceHistory(sku = p2.sku)
for (i in 5 downTo 1) {
if (i == 5) {
// current price
priceRepo.save(ProductPrice(sku = p1.sku, price = i.toDouble()))
priceRepo.save(ProductPrice(sku = p2.sku, price = (i * 2).toDouble()))
// current price history
h1.prices.add(PriceEntry(price = i.toDouble()))
h2.prices.add(PriceEntry(price = (i * 2).toDouble()))
} else {
// previous price
val expiredDate = Date(ZonedDateTime.now()
.minusMonths(i.toLong())
.toInstant()
.toEpochMilli())
h1.prices.add(PriceEntry(price = i.toDouble(), expired = expiredDate))
h2.prices.add(PriceEntry(price = (i * 2).toDouble(), expired = expiredDate))
}
}
priceHistoryRepo.saveAll(listOf(h1, h2))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment