Я пытаюсь написать простой генератор мира, используя kotlin, springboot и hibernate, и у меня много связей в сущностях, но одно из них не работает. Программа генерирует Страны и города, но в БД у меня есть нулевой идентификатор для «столицы»
Объекты:
@Entity
data class City(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id:Long? = null,
val name: String,
@OneToMany
@JoinColumn(name="CityId")
val flats: List<Flat>)
@Entity
data class Country(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id:Long? = null,
val name: String,
@OneToOne(fetch = FetchType.EAGER)
val capital: City,
@OneToMany
@JoinColumn(name="CountryId")
val cities: List<City>)
Генератор стран:
@Component
class CountryGenerator @Autowired constructor(val util: Util) {
fun getRandomCountry(): Country = util.getObj(
Country(null,
gen.country().name(),
CityGenerator(util).getRandomCapital(),
getCities())
) as Country
private fun getCities(): List<City> =
IntStream.range(0, rnd.nextInt(MAX_CITIES_NUMBER!!) + MIN_CITIES_NUMBER!!)
.mapToObj { CityGenerator(util).getRandomCity() }
.toList()
}
Генератор городов :
@Component
class CityGenerator @Autowired constructor(val util: Util) {
fun getRandomCity() = util.getObj(
City(null,
getCityName(),
getListOfFlats())
) as City
fun getRandomCapital() = util.getObj(
City(null,
getCapital(),
getListOfFlats())
) as City
private fun getListOfFlats(): List<Flat> =
IntStream.range(0, rnd.nextInt(MAX_FLATS_NUMBER!!) + MIN_FLATS_NUMBER!!)
.mapToObj { FlatGenerator(util).getFlat() }
.toList()
private fun getCapital() = gen.country().capital()
private fun getCityName(): String = gen.address().city()
}
Есть идеи, что с ним не так?
РЕДАКТИРОВАНИЕ:
Сохранение в БД:
@Component
class Util(private val personRepository: PersonRepository,
private val flatRepository: FlatRepository,
private val cityRepository: CityRepository,
private val countryRepository: CountryRepository,
private val worldRepository: WorldRepository) {
fun getObj(obj: Any): Any {
return when (obj) {
is Person -> this.personRepository.save(obj)
is Flat -> flatRepository.save(obj)
is City -> cityRepository.save(obj)
is Country -> countryRepository.save(obj)
is World -> worldRepository.save(obj)
else -> throw IllegalArgumentException("Wrong object");
}
}
РЕДАКТИРОВАНИЕ2:
Метод Util.getObj () возвращает правильные объекты: