package com.example.customerapi import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.CommandLineRunner import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.stereotype.Repository import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import java.io.Serializable import kotlin.random.Random @SpringBootApplication class CustomerApiApplication @Autowired constructor( private val customerRepository: CustomerRepository, ) : CommandLineRunner { override fun run(vararg args: String?) { val customer = Customer.create("Sambo - ${Random.nextInt(1000)}", "Chea - ${Random.nextInt(1000)}") val saved = customerRepository.save(customer) println(saved) } } fun main(args: Array) { runApplication(*args) } @Document data class Customer( @Id val id: String? = null, var firstName: String, var lastName: String, ) : Serializable { companion object { fun create( firstName: String, lastName: String ): Customer { return Customer(null, firstName, lastName) } } } @Repository interface CustomerRepository : MongoRepository @RestController @RequestMapping("/customers") class CustomerController @Autowired constructor( private val customerRepository: CustomerRepository ) { @GetMapping fun getAllCustomers(): Collection { return customerRepository.findAll() } @GetMapping("/create") fun createCustomer(): Customer? { val customer = Customer.create("Sambo - ${Random.nextInt(1000)}", "Chea - ${Random.nextInt(1000)}") return customerRepository.save(customer) } }