Created
August 30, 2018 13:25
-
-
Save mustafo/5dfe0166decb5e9cd156c0703e9346e1 to your computer and use it in GitHub Desktop.
Working one to many JDBI mapping
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.jupiter.api.Test | |
import tj.alif.core.app.db.RepositoryTest | |
import org.jdbi.v3.core.result.RowView | |
import java.lang.Integer | |
data class Contact ( | |
val id: Int, | |
val name: String, | |
var phones: MutableList<Phone> = mutableListOf() | |
) { | |
fun addPhone(phone: Phone) = phones.add(phone) | |
} | |
data class Phone (val phone_id: Integer, | |
val type: String, | |
val number: String | |
) | |
class ContactPhonesTest: RepositoryTest() { | |
@Test | |
fun `some test`() { | |
val SELECT_ALL = ("select contacts.id, name, " | |
+ "phones.id phone_id, type, phones.number " | |
+ "from contacts left join phones on contacts.id = phones.contact_id") | |
val contacts = db.createQuery(SELECT_ALL) | |
// .registerRowMapper(BeanMapper.factory(Contact::class.java, "c")) | |
// .registerRowMapper(BeanMapper.factory(Phone::class.java, "p")) | |
.reduceRows(linkedMapOf()) { map: LinkedHashMap<Int, Contact>, rowView: RowView -> | |
val contact = map.computeIfAbsent(rowView.getColumn("id", Integer::class.java) as Int) { | |
rowView.getRow(Contact::class.java) | |
} | |
if (rowView.getColumn("phone_id", Integer::class.java) != null) { | |
contact.addPhone(rowView.getRow(Phone::class.java)) | |
} | |
map | |
} | |
.toList() | |
println(contacts) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment