-
Notifications
You must be signed in to change notification settings - Fork 14
JDBC
Mario Arias edited this page Feb 22, 2016
·
13 revisions
This module has extensive support for many common uses of Spring JDBC Module
Now is more easy to add arguments to a PrepareStatement
import org.kotlinprimavera.jdbc.core.*
val prepareStatement = connection!!.prepareStatement("select * from programmer where main_language = ? and age > ?")!!
prepareStatement.arguments{
string[1] = "python"
int[2] = "30"
}
ResultSet
get support to build object easily
return rs.extract {
val pet = JdbcPet()
pet.id = int["id"]
pet.name = string["name"]
pet.birthDate = DateTime(date["birth_date"])
pet.typeId = int["type_id"]
pet.ownerId = int["owner_id"]
pet
}
Compared to:
JdbcPet pet = new JdbcPet();
pet.setId(rs.getInt("id"));
pet.setName(rs.getString("name"));
Date birthDate = rs.getDate("birth_date");
pet.setBirthDate(new DateTime(birthDate));
pet.setTypeId(rs.getInt("type_id"));
pet.setOwnerId(rs.getInt("owner_id"));
return pet;
Due to the great support for SAM in Kotlin JdbcOperations
don't need a lot of Extension Functions. I just add few to deal with vararg arguments
jdbcTemplate.query("SELECT specialty_id FROM vet_specialties WHERE vet_id=?", vet.id!!) { rs, row ->
rs.extract {
int[1]!!
}
}
KotlinPrimavera add more ways to constructs SqlParameterSource
import org.kotlinprimavera.jdbc.core.namedparam.*
//From a bean
val sps: BeanPropertySqlParameterSource = myBean.toSqlParameterSource()
//From a map
val msps: MapSqlParameterSource = myMap.toSqlParameterSource()
Also MapSqlParameterSource
get map-like operations
fun createVisitParameterSource(visit: Visit): MapSqlParameterSource {
val source = MapSqlParameterSource()
source["id"] = visit.id
source["visit_date"] = visit.date.toDate()!!
source["description"] = visit.description!!
source["pet_id"] = visit.pet!!.id!!
return source
}
if you don't want to deal with EmptyResultDataAccessException
you could use two functions
If you prefer dealing with nulls
val pet: Pet? = emptyResultToNull{
myRepository.findById(i)
}
Or with funKTionale's Option
val pet: Option<Pet> = emptyResultToOption{
myRepository.findById(i)
}
To use this module in your project
<dependency>
<groupId>org.kotlinprimavera</groupId>
<artifactId>jdbc</artifactId>
<version>0.5</version>
</dependency>