I am writing a program in Kotlin which parses some input data and writes it to a MySQL database (through JDBC).
The database includes tables such as users
and each table has a corresponding data class representing the entity:
data class User(val id: Int, val surname: String, val forename: String, ...)
The users
table has a primary key (the ID) which links it to other tables: I will call these the foos
and bars
tables, which have their associated data classes too. A user has a one-many relationship with "foo"s and "bar"s
I have classes for reading/writing to the database, such that when I do QueryManager.getAll(...)
with the appropriate parameters I can get a list of User
instances from the database.
However, when I am parsing input data, the ID of all items are unknown, so I cannot use the User
class. Also I need to store a list of "foo"s and "bar"s associated to each user but without using the Foo
and Bar
classes.
At the moment I have something which can be simplified to this:
class UserDataHolder {
// unknown userID
val userSurname: String
val userForename: String
...
val relatedFoos: List<FooDataHolder>
}
class FooDataHolder {
// unknown userID and fooID
val fooProperty1: String
val fooProperty2: Boolean
...
}
These are given to the database which then:
1. Uses the user properties to write to the users
table, getting back the auto-increment ID
2. Adds foo data to the foos
table using the user ID (but we don't know the foo ID)
3. Gets back the foo auto-increment ID to use for something else that it is linked to
Is there a common design pattern for transferring incomplete or related data like this, that I can learn about and implement in my program?
(E.g. I have read about the data transfer object on StackOverflow, this site and Martin Fowler's site but am unsure whether it is most suited here, as I am not currently aware of other patterns for similar/related problems.)
Edit: To clarify, I want to know what design patterns exist for solving a problem like this.
User
has multipleFoo
s so it's more about a pattern which allows me to represent these while excluding their IDs.