Kotlin support
Doma supports Kotlin 1.4.0 or later.
Best practices
Here are some recommended methods, such as defining classes and building them with Kotlin.
Entity classes
Define as a plain class
Specify a
Metamodel
annotation to themetamodel
element of@Entity
@Entity(metamodel = Metamodel())
class Person : AbstractPerson() {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Int = -1
var name: Name? = null
var age: Int? = -1
var address: Address? = null
@Column(name = "DEPARTMENT_ID")
var departmentId: Int = -1
@Version
var version: Int = -1
}
Domain classes
Define as a data class
Define only one constructor
Define only one property whose name is
value
in the constructorUse val for the property definition
@Domain(valueType = String::class)
data class Name(val value: String)
Embeddable classes
Define as a data class
Define only one constructor
Define properties only in the constructor
Use val for the property definitions
@Embeddable
data class Address(val city: String, val street: String)
Dao interfaces
Specify a SQL template to
@org.seasar.doma.Sql
@Dao
interface PersonDao {
@Sql("""
select * from person where id = /*id*/0
""")
@Select
fun selectById(id: Int): Person
@Insert
fun insert(person: Person): Int
}
val dao: PersonDao = ...
val person = Person(name = Name("John"), address = Address(city = "Tokyo", street = "Yaesu"))
val count = dao.insert(person)
Kotlin specific Criteria API
Note
Prefer the Kotlin specific Criteria API to DAO interfaces.
Doma provides KQueryDsl
, a Criteria API specifically for Kotlin.
It is very similar with the QueryDsl
, which is described in Unified Criteria API.
The biggest feature of the KQueryDsl
is simplicity.
val queryDsl = KQueryDsl(config)
val e = Employee_()
val list = queryDsl
.from(e)
.where {
eq(e.departmentId, 2)
isNotNull(e.managerId)
or {
gt(e.salary, Salary("1000"))
lt(e.salary, Salary("2000"))
}
}
.fetch()
You can see mode sample code here.
The KQueryDsl
is included in the doma-kotlin module.
Note that you should depend on doma-kotlin instead of doma-core in your build script.
You can write build.gradle.kts as follows:
dependencies {
implementation("org.seasar.doma:doma-kotlin:3.6.0")
}
Code Generation
Use Doma CodeGen Plugin. This plugin support Kotlin code generation.
Using kapt in Gradle
Annotation processors are supported in Kotlin with the kapt compiler plugin.
Add the dependencies using the kapt and implementation configuration in your dependencies block. For example, you can write build.gradle.kts as follows:
dependencies {
kapt("org.seasar.doma:doma-processor:3.6.0")
implementation("org.seasar.doma:doma-kotlin:3.6.0")
}
To simplify your build script, we recommend you use the Doma Compile Plugin: