Certainly! Here is an example of an API for managing accounts using Kotlin, Spring Boot, and the clean architecture principles, with a MySQL database running on localhost:3306:
First, let's define theAccount entity and the AccountRepository interface:
import javax.persistence.*
@Entity
@Table(name = "accounts")
data class Account(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long,
val name: String
)
import org.springframework.data.jpa.repository.JpaRepository
interface AccountRepository : JpaRepository<Account, Long>
Next, let's define the AccountService interface:
interface AccountService {
fun getAccounts(): List<Account>
fun createAccount(account: Account): Account
fun updateAccount(id: Long, account: Account): Account
fun deleteAccount(id: Long)
}
Now, let's implement the AccountService interface and the AccountController:
import org.springframework.stereotype.Service
@Service
class AccountServiceImpl(private val accountRepository: AccountRepository) : AccountService {
override fun getAccounts() = accountRepository.findAll()
override fun createAccount(account: Account) = accountRepository.save(account)
override fun updateAccount(id: Long, account: Account): Account {
val existingAccount = accountRepository.findById(id).orElseThrow { NotFoundException() }
val updatedAccount = existingAccount.copy(name = account.name)
return accountRepository.save(updatedAccount)
}
override fun deleteAccount(id: Long) = accountRepository.deleteById(id)
}
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/accounts")
class AccountController(private val accountService: AccountService) {
@GetMapping
fun getAccounts() = accountService.getAccounts()
@PostMapping
fun createAccount(@RequestBody account: Account): Account {
return accountService.createAccount(account)
}
@PutMapping("/{id}")
fun updateAccount(@PathVariable id: Long, @RequestBody account: Account): Account {
return accountService.updateAccount(id, account)
}
@DeleteMapping("/{id}")
fun deleteAccount(@PathVariable id: Long) {
return accountService.deleteAccount(id)
}
}
Finally, let's configure the MySQL database in the application.yml file:
spring:
jpa:
generate-ddl: true
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5InnoDBDialect
datasource:
url: jdbc:mysql://localhost:3306/accounts_db
username: user
password: password
This API has four endpoints, just like in the previous example:
GET /accounts: Returns a