Kotlin Data Class: How generate an MongoDB ObjectId for an embedded document










-1















I'm building an API with Spring Boot and Kotlin. I am trying to generate a structure the following way in MongoDB.



enter image description here



I understand that in MongoDb the concept of relationships between entities does not exist, so I will use the strategy of embedded documents. That is, to embed the Reunión in the Proyecto, and the Participante in the Reunión.



I have a main class called Proyecto and NewProyecto, that contains as property a list of reuniones of type NewReunion. I use two different classes to create and return data.



Proyecto.kt



@Document(collection = "proyectos")
@TypeAlias("proyecto")
data class Proyecto (
@Id
val id: String,
val nombre: String,
val area: String,
val fecha:String,
val reuniones: List<Reunion>?
)

@Document(collection = "proyectos")
@TypeAlias("newproyecto")
data class NewProyecto (
@Id
val id: String?,//Es posiblemente nulo porqué se crea automáticamente
var nombre: String,
var area: String,
var fecha:String,
var reuniones: List<NewReunion>?
)


Now, to create 'reuniones' I have two classes, Reunion and NewReunion. The class that corresponds to create a MongoDB embedded document is NewReunion.



NewReunion.kt



@Document
data class Reunion(
val objetivo: String,
val fecha: String,
val participantes: List<Participante>?
)

@Document
data class NewReunion(
var id: String? = ObjectId().toHexString(),
var fecha: String,
var participantes: List<NewParticipante>?
)


This is where I have the problem. I want to generate an ObjectId for this NewReunion class, so that each object embedded in it has an id. The problem is that ObjectId ().ToHexString() is not generating any value at the time that the object of type NewReunion is built, but the other data that are objetivo and fecha are filled with the data that comes from the request POST.



How I send the information.



The information I send via POST. This request is handled by a Controller named ProyectoController.kt



ProyectoController.kt



@PostMapping("/")
fun createProyecto(@RequestBody newProyecto: NewProyecto): NewProyecto = proyectoService.createProyecto(newProyecto)


ProyectoRepository.kt



interface ProyectoRepository : MongoRepository<Proyecto, String> 
fun findById(id: ObjectId): Proyecto
override fun findAll(): List<Proyecto>
fun insert(proyecto: NewProyecto): NewProyecto
fun save(proyect: Proyecto): Proyecto
fun deleteById(id: ObjectId)



ProyectoService.kt



@Service("proyectoService")
class ProyectoServiceImpl : ProyectoService
@Autowired
lateinit var proyectoRepository: ProyectoRepository

//Obtener un proyecto
override fun findById(id: ObjectId): Proyecto = proyectoRepository.findById(id)

//Obtener todos los proyectos
override fun findAll(): List<Proyecto> = proyectoRepository.findAll()

//Crear un proyecto
override fun createProyecto(newProyecto: NewProyecto): NewProyecto = proyectoRepository.insert(newProyecto)

//Actualizar un proyecto
override fun updateProyecto(proyecto: Proyecto):Proyecto = proyectoRepository.save(proyecto)

//Eliminar un proyecto
override fun deleteProyecto(id:ObjectId) = proyectoRepository.deleteById(id)



POST using Postman:



To send the information I am using Postman, and I send the request in the following way.
enter image description here



At the time of creating the new Proyecto, I return it to see the result which returns a result with id=null, but all other fields do assign the corresponding value:



enter image description here



Now, I tried initializing all the constructor parameters of the NewReunion class to see what happened.



data class NewReunion(
@Id
var id: String? = ObjectId().toHexString(),
var objetivo: String = "",
var fecha: String = ""
)


the value for the id is generated correctly together with the other values. It is just this behavior that I do not understand why I need to initialize constructor parameters of the NewReunion class.



Result of POST with the parameters initialized.



enter image description here



build.gradle



buildscript 
ext.kotlin_version = '1.2.71'
ext
kotlinVersion = '1.2.71'
springBootVersion = '2.0.6.RELEASE'

repositories
mavenCentral()

dependencies
classpath("org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion")
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"



apply plugin: 'kotlin'
apply plugin: 'kotlin-spring'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'

group = 'com.gibranlara'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
compileKotlin
kotlinOptions
freeCompilerArgs = ["-Xjsr305=strict"]
jvmTarget = "1.8"


compileTestKotlin
kotlinOptions
freeCompilerArgs = ["-Xjsr305=strict"]
jvmTarget = "1.8"



repositories
mavenCentral()


configurations
providedRuntime


dependencies
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // Required for Kotlin integration
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
compile "org.springframework.boot:spring-boot-starter-data-mongodb"
compile 'org.springframework.boot:spring-boot-starter-web'










share|improve this question



















  • 1





    where does it get values for objetivo and fecha if they were empty? I think that examples are not complete. Also I think this post lacks information about used libraries

    – asm0dey
    Nov 10 '18 at 21:50











  • @asm0dey objetivo and fecha when creating a new instance should not be empty, so I do not have the properties marked with ?. The information comes from a post made with postman.

    – Gibrán
    Nov 10 '18 at 22:28












  • @asm0dey I have edited my question to give more context.

    – Gibrán
    Nov 10 '18 at 22:44






  • 1





    @Gibrán, I've put up a demo of what I think you want to achieve, check it out. github.com/andre-artus/kotlin-optional-param-spring-demo If that look like what you want I can explain it further here.

    – Andre Artus
    Nov 14 '18 at 19:21






  • 1





    Cool. You should probably edit your question to reflect that you were having an issue using Kotlin default parameters in Spring Boot. The question as it stands now is probably not very helpful to others, which is probably why someone down-voted it. You can raise an issue on the GitHub repo I posted if you want to discuss this further. Or take it to chat.

    – Andre Artus
    Nov 14 '18 at 23:54















-1















I'm building an API with Spring Boot and Kotlin. I am trying to generate a structure the following way in MongoDB.



enter image description here



I understand that in MongoDb the concept of relationships between entities does not exist, so I will use the strategy of embedded documents. That is, to embed the Reunión in the Proyecto, and the Participante in the Reunión.



I have a main class called Proyecto and NewProyecto, that contains as property a list of reuniones of type NewReunion. I use two different classes to create and return data.



Proyecto.kt



@Document(collection = "proyectos")
@TypeAlias("proyecto")
data class Proyecto (
@Id
val id: String,
val nombre: String,
val area: String,
val fecha:String,
val reuniones: List<Reunion>?
)

@Document(collection = "proyectos")
@TypeAlias("newproyecto")
data class NewProyecto (
@Id
val id: String?,//Es posiblemente nulo porqué se crea automáticamente
var nombre: String,
var area: String,
var fecha:String,
var reuniones: List<NewReunion>?
)


Now, to create 'reuniones' I have two classes, Reunion and NewReunion. The class that corresponds to create a MongoDB embedded document is NewReunion.



NewReunion.kt



@Document
data class Reunion(
val objetivo: String,
val fecha: String,
val participantes: List<Participante>?
)

@Document
data class NewReunion(
var id: String? = ObjectId().toHexString(),
var fecha: String,
var participantes: List<NewParticipante>?
)


This is where I have the problem. I want to generate an ObjectId for this NewReunion class, so that each object embedded in it has an id. The problem is that ObjectId ().ToHexString() is not generating any value at the time that the object of type NewReunion is built, but the other data that are objetivo and fecha are filled with the data that comes from the request POST.



How I send the information.



The information I send via POST. This request is handled by a Controller named ProyectoController.kt



ProyectoController.kt



@PostMapping("/")
fun createProyecto(@RequestBody newProyecto: NewProyecto): NewProyecto = proyectoService.createProyecto(newProyecto)


ProyectoRepository.kt



interface ProyectoRepository : MongoRepository<Proyecto, String> 
fun findById(id: ObjectId): Proyecto
override fun findAll(): List<Proyecto>
fun insert(proyecto: NewProyecto): NewProyecto
fun save(proyect: Proyecto): Proyecto
fun deleteById(id: ObjectId)



ProyectoService.kt



@Service("proyectoService")
class ProyectoServiceImpl : ProyectoService
@Autowired
lateinit var proyectoRepository: ProyectoRepository

//Obtener un proyecto
override fun findById(id: ObjectId): Proyecto = proyectoRepository.findById(id)

//Obtener todos los proyectos
override fun findAll(): List<Proyecto> = proyectoRepository.findAll()

//Crear un proyecto
override fun createProyecto(newProyecto: NewProyecto): NewProyecto = proyectoRepository.insert(newProyecto)

//Actualizar un proyecto
override fun updateProyecto(proyecto: Proyecto):Proyecto = proyectoRepository.save(proyecto)

//Eliminar un proyecto
override fun deleteProyecto(id:ObjectId) = proyectoRepository.deleteById(id)



POST using Postman:



To send the information I am using Postman, and I send the request in the following way.
enter image description here



At the time of creating the new Proyecto, I return it to see the result which returns a result with id=null, but all other fields do assign the corresponding value:



enter image description here



Now, I tried initializing all the constructor parameters of the NewReunion class to see what happened.



data class NewReunion(
@Id
var id: String? = ObjectId().toHexString(),
var objetivo: String = "",
var fecha: String = ""
)


the value for the id is generated correctly together with the other values. It is just this behavior that I do not understand why I need to initialize constructor parameters of the NewReunion class.



Result of POST with the parameters initialized.



enter image description here



build.gradle



buildscript 
ext.kotlin_version = '1.2.71'
ext
kotlinVersion = '1.2.71'
springBootVersion = '2.0.6.RELEASE'

repositories
mavenCentral()

dependencies
classpath("org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion")
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"



apply plugin: 'kotlin'
apply plugin: 'kotlin-spring'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'

group = 'com.gibranlara'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
compileKotlin
kotlinOptions
freeCompilerArgs = ["-Xjsr305=strict"]
jvmTarget = "1.8"


compileTestKotlin
kotlinOptions
freeCompilerArgs = ["-Xjsr305=strict"]
jvmTarget = "1.8"



repositories
mavenCentral()


configurations
providedRuntime


dependencies
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // Required for Kotlin integration
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
compile "org.springframework.boot:spring-boot-starter-data-mongodb"
compile 'org.springframework.boot:spring-boot-starter-web'










share|improve this question



















  • 1





    where does it get values for objetivo and fecha if they were empty? I think that examples are not complete. Also I think this post lacks information about used libraries

    – asm0dey
    Nov 10 '18 at 21:50











  • @asm0dey objetivo and fecha when creating a new instance should not be empty, so I do not have the properties marked with ?. The information comes from a post made with postman.

    – Gibrán
    Nov 10 '18 at 22:28












  • @asm0dey I have edited my question to give more context.

    – Gibrán
    Nov 10 '18 at 22:44






  • 1





    @Gibrán, I've put up a demo of what I think you want to achieve, check it out. github.com/andre-artus/kotlin-optional-param-spring-demo If that look like what you want I can explain it further here.

    – Andre Artus
    Nov 14 '18 at 19:21






  • 1





    Cool. You should probably edit your question to reflect that you were having an issue using Kotlin default parameters in Spring Boot. The question as it stands now is probably not very helpful to others, which is probably why someone down-voted it. You can raise an issue on the GitHub repo I posted if you want to discuss this further. Or take it to chat.

    – Andre Artus
    Nov 14 '18 at 23:54













-1












-1








-1








I'm building an API with Spring Boot and Kotlin. I am trying to generate a structure the following way in MongoDB.



enter image description here



I understand that in MongoDb the concept of relationships between entities does not exist, so I will use the strategy of embedded documents. That is, to embed the Reunión in the Proyecto, and the Participante in the Reunión.



I have a main class called Proyecto and NewProyecto, that contains as property a list of reuniones of type NewReunion. I use two different classes to create and return data.



Proyecto.kt



@Document(collection = "proyectos")
@TypeAlias("proyecto")
data class Proyecto (
@Id
val id: String,
val nombre: String,
val area: String,
val fecha:String,
val reuniones: List<Reunion>?
)

@Document(collection = "proyectos")
@TypeAlias("newproyecto")
data class NewProyecto (
@Id
val id: String?,//Es posiblemente nulo porqué se crea automáticamente
var nombre: String,
var area: String,
var fecha:String,
var reuniones: List<NewReunion>?
)


Now, to create 'reuniones' I have two classes, Reunion and NewReunion. The class that corresponds to create a MongoDB embedded document is NewReunion.



NewReunion.kt



@Document
data class Reunion(
val objetivo: String,
val fecha: String,
val participantes: List<Participante>?
)

@Document
data class NewReunion(
var id: String? = ObjectId().toHexString(),
var fecha: String,
var participantes: List<NewParticipante>?
)


This is where I have the problem. I want to generate an ObjectId for this NewReunion class, so that each object embedded in it has an id. The problem is that ObjectId ().ToHexString() is not generating any value at the time that the object of type NewReunion is built, but the other data that are objetivo and fecha are filled with the data that comes from the request POST.



How I send the information.



The information I send via POST. This request is handled by a Controller named ProyectoController.kt



ProyectoController.kt



@PostMapping("/")
fun createProyecto(@RequestBody newProyecto: NewProyecto): NewProyecto = proyectoService.createProyecto(newProyecto)


ProyectoRepository.kt



interface ProyectoRepository : MongoRepository<Proyecto, String> 
fun findById(id: ObjectId): Proyecto
override fun findAll(): List<Proyecto>
fun insert(proyecto: NewProyecto): NewProyecto
fun save(proyect: Proyecto): Proyecto
fun deleteById(id: ObjectId)



ProyectoService.kt



@Service("proyectoService")
class ProyectoServiceImpl : ProyectoService
@Autowired
lateinit var proyectoRepository: ProyectoRepository

//Obtener un proyecto
override fun findById(id: ObjectId): Proyecto = proyectoRepository.findById(id)

//Obtener todos los proyectos
override fun findAll(): List<Proyecto> = proyectoRepository.findAll()

//Crear un proyecto
override fun createProyecto(newProyecto: NewProyecto): NewProyecto = proyectoRepository.insert(newProyecto)

//Actualizar un proyecto
override fun updateProyecto(proyecto: Proyecto):Proyecto = proyectoRepository.save(proyecto)

//Eliminar un proyecto
override fun deleteProyecto(id:ObjectId) = proyectoRepository.deleteById(id)



POST using Postman:



To send the information I am using Postman, and I send the request in the following way.
enter image description here



At the time of creating the new Proyecto, I return it to see the result which returns a result with id=null, but all other fields do assign the corresponding value:



enter image description here



Now, I tried initializing all the constructor parameters of the NewReunion class to see what happened.



data class NewReunion(
@Id
var id: String? = ObjectId().toHexString(),
var objetivo: String = "",
var fecha: String = ""
)


the value for the id is generated correctly together with the other values. It is just this behavior that I do not understand why I need to initialize constructor parameters of the NewReunion class.



Result of POST with the parameters initialized.



enter image description here



build.gradle



buildscript 
ext.kotlin_version = '1.2.71'
ext
kotlinVersion = '1.2.71'
springBootVersion = '2.0.6.RELEASE'

repositories
mavenCentral()

dependencies
classpath("org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion")
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"



apply plugin: 'kotlin'
apply plugin: 'kotlin-spring'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'

group = 'com.gibranlara'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
compileKotlin
kotlinOptions
freeCompilerArgs = ["-Xjsr305=strict"]
jvmTarget = "1.8"


compileTestKotlin
kotlinOptions
freeCompilerArgs = ["-Xjsr305=strict"]
jvmTarget = "1.8"



repositories
mavenCentral()


configurations
providedRuntime


dependencies
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // Required for Kotlin integration
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
compile "org.springframework.boot:spring-boot-starter-data-mongodb"
compile 'org.springframework.boot:spring-boot-starter-web'










share|improve this question
















I'm building an API with Spring Boot and Kotlin. I am trying to generate a structure the following way in MongoDB.



enter image description here



I understand that in MongoDb the concept of relationships between entities does not exist, so I will use the strategy of embedded documents. That is, to embed the Reunión in the Proyecto, and the Participante in the Reunión.



I have a main class called Proyecto and NewProyecto, that contains as property a list of reuniones of type NewReunion. I use two different classes to create and return data.



Proyecto.kt



@Document(collection = "proyectos")
@TypeAlias("proyecto")
data class Proyecto (
@Id
val id: String,
val nombre: String,
val area: String,
val fecha:String,
val reuniones: List<Reunion>?
)

@Document(collection = "proyectos")
@TypeAlias("newproyecto")
data class NewProyecto (
@Id
val id: String?,//Es posiblemente nulo porqué se crea automáticamente
var nombre: String,
var area: String,
var fecha:String,
var reuniones: List<NewReunion>?
)


Now, to create 'reuniones' I have two classes, Reunion and NewReunion. The class that corresponds to create a MongoDB embedded document is NewReunion.



NewReunion.kt



@Document
data class Reunion(
val objetivo: String,
val fecha: String,
val participantes: List<Participante>?
)

@Document
data class NewReunion(
var id: String? = ObjectId().toHexString(),
var fecha: String,
var participantes: List<NewParticipante>?
)


This is where I have the problem. I want to generate an ObjectId for this NewReunion class, so that each object embedded in it has an id. The problem is that ObjectId ().ToHexString() is not generating any value at the time that the object of type NewReunion is built, but the other data that are objetivo and fecha are filled with the data that comes from the request POST.



How I send the information.



The information I send via POST. This request is handled by a Controller named ProyectoController.kt



ProyectoController.kt



@PostMapping("/")
fun createProyecto(@RequestBody newProyecto: NewProyecto): NewProyecto = proyectoService.createProyecto(newProyecto)


ProyectoRepository.kt



interface ProyectoRepository : MongoRepository<Proyecto, String> 
fun findById(id: ObjectId): Proyecto
override fun findAll(): List<Proyecto>
fun insert(proyecto: NewProyecto): NewProyecto
fun save(proyect: Proyecto): Proyecto
fun deleteById(id: ObjectId)



ProyectoService.kt



@Service("proyectoService")
class ProyectoServiceImpl : ProyectoService
@Autowired
lateinit var proyectoRepository: ProyectoRepository

//Obtener un proyecto
override fun findById(id: ObjectId): Proyecto = proyectoRepository.findById(id)

//Obtener todos los proyectos
override fun findAll(): List<Proyecto> = proyectoRepository.findAll()

//Crear un proyecto
override fun createProyecto(newProyecto: NewProyecto): NewProyecto = proyectoRepository.insert(newProyecto)

//Actualizar un proyecto
override fun updateProyecto(proyecto: Proyecto):Proyecto = proyectoRepository.save(proyecto)

//Eliminar un proyecto
override fun deleteProyecto(id:ObjectId) = proyectoRepository.deleteById(id)



POST using Postman:



To send the information I am using Postman, and I send the request in the following way.
enter image description here



At the time of creating the new Proyecto, I return it to see the result which returns a result with id=null, but all other fields do assign the corresponding value:



enter image description here



Now, I tried initializing all the constructor parameters of the NewReunion class to see what happened.



data class NewReunion(
@Id
var id: String? = ObjectId().toHexString(),
var objetivo: String = "",
var fecha: String = ""
)


the value for the id is generated correctly together with the other values. It is just this behavior that I do not understand why I need to initialize constructor parameters of the NewReunion class.



Result of POST with the parameters initialized.



enter image description here



build.gradle



buildscript 
ext.kotlin_version = '1.2.71'
ext
kotlinVersion = '1.2.71'
springBootVersion = '2.0.6.RELEASE'

repositories
mavenCentral()

dependencies
classpath("org.springframework.boot:spring-boot-gradle-plugin:$springBootVersion")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
classpath("org.jetbrains.kotlin:kotlin-allopen:$kotlinVersion")
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"



apply plugin: 'kotlin'
apply plugin: 'kotlin-spring'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'

group = 'com.gibranlara'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
compileKotlin
kotlinOptions
freeCompilerArgs = ["-Xjsr305=strict"]
jvmTarget = "1.8"


compileTestKotlin
kotlinOptions
freeCompilerArgs = ["-Xjsr305=strict"]
jvmTarget = "1.8"



repositories
mavenCentral()


configurations
providedRuntime


dependencies
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" // Required for Kotlin integration
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
compile "org.springframework.boot:spring-boot-starter-data-mongodb"
compile 'org.springframework.boot:spring-boot-starter-web'







mongodb spring-mvc spring-boot kotlin






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 13:37







Gibrán

















asked Nov 10 '18 at 21:12









GibránGibrán

368




368







  • 1





    where does it get values for objetivo and fecha if they were empty? I think that examples are not complete. Also I think this post lacks information about used libraries

    – asm0dey
    Nov 10 '18 at 21:50











  • @asm0dey objetivo and fecha when creating a new instance should not be empty, so I do not have the properties marked with ?. The information comes from a post made with postman.

    – Gibrán
    Nov 10 '18 at 22:28












  • @asm0dey I have edited my question to give more context.

    – Gibrán
    Nov 10 '18 at 22:44






  • 1





    @Gibrán, I've put up a demo of what I think you want to achieve, check it out. github.com/andre-artus/kotlin-optional-param-spring-demo If that look like what you want I can explain it further here.

    – Andre Artus
    Nov 14 '18 at 19:21






  • 1





    Cool. You should probably edit your question to reflect that you were having an issue using Kotlin default parameters in Spring Boot. The question as it stands now is probably not very helpful to others, which is probably why someone down-voted it. You can raise an issue on the GitHub repo I posted if you want to discuss this further. Or take it to chat.

    – Andre Artus
    Nov 14 '18 at 23:54












  • 1





    where does it get values for objetivo and fecha if they were empty? I think that examples are not complete. Also I think this post lacks information about used libraries

    – asm0dey
    Nov 10 '18 at 21:50











  • @asm0dey objetivo and fecha when creating a new instance should not be empty, so I do not have the properties marked with ?. The information comes from a post made with postman.

    – Gibrán
    Nov 10 '18 at 22:28












  • @asm0dey I have edited my question to give more context.

    – Gibrán
    Nov 10 '18 at 22:44






  • 1





    @Gibrán, I've put up a demo of what I think you want to achieve, check it out. github.com/andre-artus/kotlin-optional-param-spring-demo If that look like what you want I can explain it further here.

    – Andre Artus
    Nov 14 '18 at 19:21






  • 1





    Cool. You should probably edit your question to reflect that you were having an issue using Kotlin default parameters in Spring Boot. The question as it stands now is probably not very helpful to others, which is probably why someone down-voted it. You can raise an issue on the GitHub repo I posted if you want to discuss this further. Or take it to chat.

    – Andre Artus
    Nov 14 '18 at 23:54







1




1





where does it get values for objetivo and fecha if they were empty? I think that examples are not complete. Also I think this post lacks information about used libraries

– asm0dey
Nov 10 '18 at 21:50





where does it get values for objetivo and fecha if they were empty? I think that examples are not complete. Also I think this post lacks information about used libraries

– asm0dey
Nov 10 '18 at 21:50













@asm0dey objetivo and fecha when creating a new instance should not be empty, so I do not have the properties marked with ?. The information comes from a post made with postman.

– Gibrán
Nov 10 '18 at 22:28






@asm0dey objetivo and fecha when creating a new instance should not be empty, so I do not have the properties marked with ?. The information comes from a post made with postman.

– Gibrán
Nov 10 '18 at 22:28














@asm0dey I have edited my question to give more context.

– Gibrán
Nov 10 '18 at 22:44





@asm0dey I have edited my question to give more context.

– Gibrán
Nov 10 '18 at 22:44




1




1





@Gibrán, I've put up a demo of what I think you want to achieve, check it out. github.com/andre-artus/kotlin-optional-param-spring-demo If that look like what you want I can explain it further here.

– Andre Artus
Nov 14 '18 at 19:21





@Gibrán, I've put up a demo of what I think you want to achieve, check it out. github.com/andre-artus/kotlin-optional-param-spring-demo If that look like what you want I can explain it further here.

– Andre Artus
Nov 14 '18 at 19:21




1




1





Cool. You should probably edit your question to reflect that you were having an issue using Kotlin default parameters in Spring Boot. The question as it stands now is probably not very helpful to others, which is probably why someone down-voted it. You can raise an issue on the GitHub repo I posted if you want to discuss this further. Or take it to chat.

– Andre Artus
Nov 14 '18 at 23:54





Cool. You should probably edit your question to reflect that you were having an issue using Kotlin default parameters in Spring Boot. The question as it stands now is probably not very helpful to others, which is probably why someone down-voted it. You can raise an issue on the GitHub repo I posted if you want to discuss this further. Or take it to chat.

– Andre Artus
Nov 14 '18 at 23:54












1 Answer
1






active

oldest

votes


















1














The library you are using is probably not written with Kotlin in mind.



Kotlin generates a synthetic constructor that loads default values prior to calling the actual constructor, e.g.



 // Java 
public NewReunion(String var1, String var2, String var3, int var4, DefaultConstructorMarker var5)
if ((var4 & 1) != 0)
var1 = ObjectId().toHexString();

this(var1, var2, var3);



The library is likely doing one of the following:



  • Calling the default constructor, then calling set[Property] matching the annotations/convention.

  • Calling the closest match constructor: NewReunion(@Nullable String id, @NotNull String objetivo, @NotNull String fecha) with NewReunion(null, "objetivo", "fecha")

If you define your class as such:



data class NewReunion @JvmOverloads constructor(
var id: String? = "",
var objetivo: String,
var fecha: String
)


You will get additional constructors e.g.



// Java
public NewReunion(@NotNull String objetivo, @NotNull String fecha)


If your library is using the first option then you may need to lazy initialize the id field in a getter (also convert data class to normal class).



An Aside



Most of these kind of problems stem from devs using the same object model for communication and business logic. Whenever I see a nullable id on an entity it like a clarion call that bugs are afoot.



Any data you get from an outside source(even if it's from a server you control) should be treated as if it was put there by your most baleful enemy, but many developers just suck it in and use it as it comes.



If you don't have something along the lines of



val cleanData = validate(inputData)


before crossing from an input layer to a business layer then you are setting yourself up for future embarrassment.



Input layers are:



  • User interface

  • Web services

  • Anything coming from outside your immediate domain of control





share|improve this answer























  • But I'm not using any library. I just initialize a new spring boot application, added the kotlin dependency and that's all. I'm using the NewReunion model only for creation. The id is null because I am not sending the ObjectId from the fron-end, but I want that when a NewReunion object is generated it generates an objectid for that object. To return the information I am using a model called Proyecto, which does not allow for null values.

    – Gibrán
    Nov 12 '18 at 15:04












  • If you are using Spring Boot then you are using not one, but many [Java] libraries. See my advice above, under "An Aside". The two models, even if they look [almost] the same, should not be forced into one. You should really have some logic in-between the two that maps from the input model (NewReunion?) to the output model (Proyecto?). That mapping function should be responsible for ensuring all fields are valid, incl.ObjectId. Use the type system to your advantage.

    – Andre Artus
    Nov 12 '18 at 23:36











  • Currently I have my model, controllers, repositories and services. I just do not know at what point it is where I should generate the id for the embedded document (NewReunion). If you allow me I can place all my code to give more context, what do you think?

    – Gibrán
    Nov 13 '18 at 0:10











  • I have already edited my question with more information.

    – Gibrán
    Nov 13 '18 at 0:47






  • 1





    That's cool, I'll have to look at it later though, as it is bedtime for me.

    – Andre Artus
    Nov 13 '18 at 2:45










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243455%2fkotlin-data-class-how-generate-an-mongodb-objectid-for-an-embedded-document%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














The library you are using is probably not written with Kotlin in mind.



Kotlin generates a synthetic constructor that loads default values prior to calling the actual constructor, e.g.



 // Java 
public NewReunion(String var1, String var2, String var3, int var4, DefaultConstructorMarker var5)
if ((var4 & 1) != 0)
var1 = ObjectId().toHexString();

this(var1, var2, var3);



The library is likely doing one of the following:



  • Calling the default constructor, then calling set[Property] matching the annotations/convention.

  • Calling the closest match constructor: NewReunion(@Nullable String id, @NotNull String objetivo, @NotNull String fecha) with NewReunion(null, "objetivo", "fecha")

If you define your class as such:



data class NewReunion @JvmOverloads constructor(
var id: String? = "",
var objetivo: String,
var fecha: String
)


You will get additional constructors e.g.



// Java
public NewReunion(@NotNull String objetivo, @NotNull String fecha)


If your library is using the first option then you may need to lazy initialize the id field in a getter (also convert data class to normal class).



An Aside



Most of these kind of problems stem from devs using the same object model for communication and business logic. Whenever I see a nullable id on an entity it like a clarion call that bugs are afoot.



Any data you get from an outside source(even if it's from a server you control) should be treated as if it was put there by your most baleful enemy, but many developers just suck it in and use it as it comes.



If you don't have something along the lines of



val cleanData = validate(inputData)


before crossing from an input layer to a business layer then you are setting yourself up for future embarrassment.



Input layers are:



  • User interface

  • Web services

  • Anything coming from outside your immediate domain of control





share|improve this answer























  • But I'm not using any library. I just initialize a new spring boot application, added the kotlin dependency and that's all. I'm using the NewReunion model only for creation. The id is null because I am not sending the ObjectId from the fron-end, but I want that when a NewReunion object is generated it generates an objectid for that object. To return the information I am using a model called Proyecto, which does not allow for null values.

    – Gibrán
    Nov 12 '18 at 15:04












  • If you are using Spring Boot then you are using not one, but many [Java] libraries. See my advice above, under "An Aside". The two models, even if they look [almost] the same, should not be forced into one. You should really have some logic in-between the two that maps from the input model (NewReunion?) to the output model (Proyecto?). That mapping function should be responsible for ensuring all fields are valid, incl.ObjectId. Use the type system to your advantage.

    – Andre Artus
    Nov 12 '18 at 23:36











  • Currently I have my model, controllers, repositories and services. I just do not know at what point it is where I should generate the id for the embedded document (NewReunion). If you allow me I can place all my code to give more context, what do you think?

    – Gibrán
    Nov 13 '18 at 0:10











  • I have already edited my question with more information.

    – Gibrán
    Nov 13 '18 at 0:47






  • 1





    That's cool, I'll have to look at it later though, as it is bedtime for me.

    – Andre Artus
    Nov 13 '18 at 2:45















1














The library you are using is probably not written with Kotlin in mind.



Kotlin generates a synthetic constructor that loads default values prior to calling the actual constructor, e.g.



 // Java 
public NewReunion(String var1, String var2, String var3, int var4, DefaultConstructorMarker var5)
if ((var4 & 1) != 0)
var1 = ObjectId().toHexString();

this(var1, var2, var3);



The library is likely doing one of the following:



  • Calling the default constructor, then calling set[Property] matching the annotations/convention.

  • Calling the closest match constructor: NewReunion(@Nullable String id, @NotNull String objetivo, @NotNull String fecha) with NewReunion(null, "objetivo", "fecha")

If you define your class as such:



data class NewReunion @JvmOverloads constructor(
var id: String? = "",
var objetivo: String,
var fecha: String
)


You will get additional constructors e.g.



// Java
public NewReunion(@NotNull String objetivo, @NotNull String fecha)


If your library is using the first option then you may need to lazy initialize the id field in a getter (also convert data class to normal class).



An Aside



Most of these kind of problems stem from devs using the same object model for communication and business logic. Whenever I see a nullable id on an entity it like a clarion call that bugs are afoot.



Any data you get from an outside source(even if it's from a server you control) should be treated as if it was put there by your most baleful enemy, but many developers just suck it in and use it as it comes.



If you don't have something along the lines of



val cleanData = validate(inputData)


before crossing from an input layer to a business layer then you are setting yourself up for future embarrassment.



Input layers are:



  • User interface

  • Web services

  • Anything coming from outside your immediate domain of control





share|improve this answer























  • But I'm not using any library. I just initialize a new spring boot application, added the kotlin dependency and that's all. I'm using the NewReunion model only for creation. The id is null because I am not sending the ObjectId from the fron-end, but I want that when a NewReunion object is generated it generates an objectid for that object. To return the information I am using a model called Proyecto, which does not allow for null values.

    – Gibrán
    Nov 12 '18 at 15:04












  • If you are using Spring Boot then you are using not one, but many [Java] libraries. See my advice above, under "An Aside". The two models, even if they look [almost] the same, should not be forced into one. You should really have some logic in-between the two that maps from the input model (NewReunion?) to the output model (Proyecto?). That mapping function should be responsible for ensuring all fields are valid, incl.ObjectId. Use the type system to your advantage.

    – Andre Artus
    Nov 12 '18 at 23:36











  • Currently I have my model, controllers, repositories and services. I just do not know at what point it is where I should generate the id for the embedded document (NewReunion). If you allow me I can place all my code to give more context, what do you think?

    – Gibrán
    Nov 13 '18 at 0:10











  • I have already edited my question with more information.

    – Gibrán
    Nov 13 '18 at 0:47






  • 1





    That's cool, I'll have to look at it later though, as it is bedtime for me.

    – Andre Artus
    Nov 13 '18 at 2:45













1












1








1







The library you are using is probably not written with Kotlin in mind.



Kotlin generates a synthetic constructor that loads default values prior to calling the actual constructor, e.g.



 // Java 
public NewReunion(String var1, String var2, String var3, int var4, DefaultConstructorMarker var5)
if ((var4 & 1) != 0)
var1 = ObjectId().toHexString();

this(var1, var2, var3);



The library is likely doing one of the following:



  • Calling the default constructor, then calling set[Property] matching the annotations/convention.

  • Calling the closest match constructor: NewReunion(@Nullable String id, @NotNull String objetivo, @NotNull String fecha) with NewReunion(null, "objetivo", "fecha")

If you define your class as such:



data class NewReunion @JvmOverloads constructor(
var id: String? = "",
var objetivo: String,
var fecha: String
)


You will get additional constructors e.g.



// Java
public NewReunion(@NotNull String objetivo, @NotNull String fecha)


If your library is using the first option then you may need to lazy initialize the id field in a getter (also convert data class to normal class).



An Aside



Most of these kind of problems stem from devs using the same object model for communication and business logic. Whenever I see a nullable id on an entity it like a clarion call that bugs are afoot.



Any data you get from an outside source(even if it's from a server you control) should be treated as if it was put there by your most baleful enemy, but many developers just suck it in and use it as it comes.



If you don't have something along the lines of



val cleanData = validate(inputData)


before crossing from an input layer to a business layer then you are setting yourself up for future embarrassment.



Input layers are:



  • User interface

  • Web services

  • Anything coming from outside your immediate domain of control





share|improve this answer













The library you are using is probably not written with Kotlin in mind.



Kotlin generates a synthetic constructor that loads default values prior to calling the actual constructor, e.g.



 // Java 
public NewReunion(String var1, String var2, String var3, int var4, DefaultConstructorMarker var5)
if ((var4 & 1) != 0)
var1 = ObjectId().toHexString();

this(var1, var2, var3);



The library is likely doing one of the following:



  • Calling the default constructor, then calling set[Property] matching the annotations/convention.

  • Calling the closest match constructor: NewReunion(@Nullable String id, @NotNull String objetivo, @NotNull String fecha) with NewReunion(null, "objetivo", "fecha")

If you define your class as such:



data class NewReunion @JvmOverloads constructor(
var id: String? = "",
var objetivo: String,
var fecha: String
)


You will get additional constructors e.g.



// Java
public NewReunion(@NotNull String objetivo, @NotNull String fecha)


If your library is using the first option then you may need to lazy initialize the id field in a getter (also convert data class to normal class).



An Aside



Most of these kind of problems stem from devs using the same object model for communication and business logic. Whenever I see a nullable id on an entity it like a clarion call that bugs are afoot.



Any data you get from an outside source(even if it's from a server you control) should be treated as if it was put there by your most baleful enemy, but many developers just suck it in and use it as it comes.



If you don't have something along the lines of



val cleanData = validate(inputData)


before crossing from an input layer to a business layer then you are setting yourself up for future embarrassment.



Input layers are:



  • User interface

  • Web services

  • Anything coming from outside your immediate domain of control






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 11 '18 at 18:42









Andre ArtusAndre Artus

1,4841118




1,4841118












  • But I'm not using any library. I just initialize a new spring boot application, added the kotlin dependency and that's all. I'm using the NewReunion model only for creation. The id is null because I am not sending the ObjectId from the fron-end, but I want that when a NewReunion object is generated it generates an objectid for that object. To return the information I am using a model called Proyecto, which does not allow for null values.

    – Gibrán
    Nov 12 '18 at 15:04












  • If you are using Spring Boot then you are using not one, but many [Java] libraries. See my advice above, under "An Aside". The two models, even if they look [almost] the same, should not be forced into one. You should really have some logic in-between the two that maps from the input model (NewReunion?) to the output model (Proyecto?). That mapping function should be responsible for ensuring all fields are valid, incl.ObjectId. Use the type system to your advantage.

    – Andre Artus
    Nov 12 '18 at 23:36











  • Currently I have my model, controllers, repositories and services. I just do not know at what point it is where I should generate the id for the embedded document (NewReunion). If you allow me I can place all my code to give more context, what do you think?

    – Gibrán
    Nov 13 '18 at 0:10











  • I have already edited my question with more information.

    – Gibrán
    Nov 13 '18 at 0:47






  • 1





    That's cool, I'll have to look at it later though, as it is bedtime for me.

    – Andre Artus
    Nov 13 '18 at 2:45

















  • But I'm not using any library. I just initialize a new spring boot application, added the kotlin dependency and that's all. I'm using the NewReunion model only for creation. The id is null because I am not sending the ObjectId from the fron-end, but I want that when a NewReunion object is generated it generates an objectid for that object. To return the information I am using a model called Proyecto, which does not allow for null values.

    – Gibrán
    Nov 12 '18 at 15:04












  • If you are using Spring Boot then you are using not one, but many [Java] libraries. See my advice above, under "An Aside". The two models, even if they look [almost] the same, should not be forced into one. You should really have some logic in-between the two that maps from the input model (NewReunion?) to the output model (Proyecto?). That mapping function should be responsible for ensuring all fields are valid, incl.ObjectId. Use the type system to your advantage.

    – Andre Artus
    Nov 12 '18 at 23:36











  • Currently I have my model, controllers, repositories and services. I just do not know at what point it is where I should generate the id for the embedded document (NewReunion). If you allow me I can place all my code to give more context, what do you think?

    – Gibrán
    Nov 13 '18 at 0:10











  • I have already edited my question with more information.

    – Gibrán
    Nov 13 '18 at 0:47






  • 1





    That's cool, I'll have to look at it later though, as it is bedtime for me.

    – Andre Artus
    Nov 13 '18 at 2:45
















But I'm not using any library. I just initialize a new spring boot application, added the kotlin dependency and that's all. I'm using the NewReunion model only for creation. The id is null because I am not sending the ObjectId from the fron-end, but I want that when a NewReunion object is generated it generates an objectid for that object. To return the information I am using a model called Proyecto, which does not allow for null values.

– Gibrán
Nov 12 '18 at 15:04






But I'm not using any library. I just initialize a new spring boot application, added the kotlin dependency and that's all. I'm using the NewReunion model only for creation. The id is null because I am not sending the ObjectId from the fron-end, but I want that when a NewReunion object is generated it generates an objectid for that object. To return the information I am using a model called Proyecto, which does not allow for null values.

– Gibrán
Nov 12 '18 at 15:04














If you are using Spring Boot then you are using not one, but many [Java] libraries. See my advice above, under "An Aside". The two models, even if they look [almost] the same, should not be forced into one. You should really have some logic in-between the two that maps from the input model (NewReunion?) to the output model (Proyecto?). That mapping function should be responsible for ensuring all fields are valid, incl.ObjectId. Use the type system to your advantage.

– Andre Artus
Nov 12 '18 at 23:36





If you are using Spring Boot then you are using not one, but many [Java] libraries. See my advice above, under "An Aside". The two models, even if they look [almost] the same, should not be forced into one. You should really have some logic in-between the two that maps from the input model (NewReunion?) to the output model (Proyecto?). That mapping function should be responsible for ensuring all fields are valid, incl.ObjectId. Use the type system to your advantage.

– Andre Artus
Nov 12 '18 at 23:36













Currently I have my model, controllers, repositories and services. I just do not know at what point it is where I should generate the id for the embedded document (NewReunion). If you allow me I can place all my code to give more context, what do you think?

– Gibrán
Nov 13 '18 at 0:10





Currently I have my model, controllers, repositories and services. I just do not know at what point it is where I should generate the id for the embedded document (NewReunion). If you allow me I can place all my code to give more context, what do you think?

– Gibrán
Nov 13 '18 at 0:10













I have already edited my question with more information.

– Gibrán
Nov 13 '18 at 0:47





I have already edited my question with more information.

– Gibrán
Nov 13 '18 at 0:47




1




1





That's cool, I'll have to look at it later though, as it is bedtime for me.

– Andre Artus
Nov 13 '18 at 2:45





That's cool, I'll have to look at it later though, as it is bedtime for me.

– Andre Artus
Nov 13 '18 at 2:45

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243455%2fkotlin-data-class-how-generate-an-mongodb-objectid-for-an-embedded-document%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)