spring data 系列一直是开发者追捧的热潮,而官方并未出spring data jdbc,国外一个开发者让我们看到了福音,文档如下供大家共同学习。
the purpose of this project is to provide generic, lightweight and easy to use dao implementation for relational databases based on from , compatible with spring data umbrella of projects.
- lightweight, fast and low-overhead. only a handful of classes, no xml, annotations, reflection
- this is not full-blown orm. no relationship handling, lazy loading, dirty checking, caching
- crud implemented in seconds
- for small applications where jpa is an overkill
- use when simplicity is needed or when future migration e.g. to jpa is considered
- minimalistic support for database dialect differences (e.g. transparent paging of results)
each dao provides built-in support for:
- mapping to/from domain objects through abstraction
- generated and user-defined primary keys
- extracting generated key
- compound (multi-column) primary keys
- immutable domain objects
- paging (requesting subset of results)
- sorting over several columns (database agnostic)
- optional support for many-to-one relationships
- supported databases (continuously tested):
- mysql
- postgresql
- h2
- hsqldb
- derby
- ms sql server (2008, 2012)
- oracle 10g / 11g (9i should work too)
- ...and most likely many others
- easily extendable to other database dialects via class.
- easy retrieval of records by id
compatible with spring data abstraction, all these methods are implemented for you:
public interface pagingandsortingrepository extends crudrepository {
t save(t entity);
iterable save(iterable entities);
t findone(id id);
boolean exists(id id);
iterable findall();
long count();
void delete(id id);
void delete(t entity);
void delete(iterable entities);
void deleteall();
iterable findall(sort sort);
page findall(pageable pageable);
iterable findall(iterable ids);
}
pageable
and sort
parameters are also fully supported, which means you get paging and sorting by arbitrary properties for free. for example say you have userrepository
extending pagingandsortingrepository
interface (implemented for you by the library) and you request 5th page of users
table, 10 per page, after applying some sorting:
page page = userrepository.findall(
new pagerequest(
5, 10,
new sort(
new order(desc, "reputation"),
new order(asc, "user_name")
)
)
);
spring data jdbc repository library will translate this call into (postgresql syntax):
select *
from users
order by reputation desc, user_name asc
limit 50 offset 10
...or even (derby syntax):
select * from (
select row_number() over () as row_num, t.*
from (
select *
from users
order by reputation desc, user_name asc
) as t
) as a
where row_num between 51 and 60
no matter which database you use, you'll get page
object in return (you still have to provide rowmapper
yourself to translate from to domain object). if you don't know spring data project yet, is a wonderful abstraction, not only encapsulating list
, but also providing metadata such as total number of records, on which page we currently are, etc.
-
you consider migration to jpa or even some nosql database in the future.
since your code will rely only on methods defined in and from umbrella project you are free to switch from implementation (from this project) to: , , or . they all implement the same common api. of course don't expect that switching from jdbc to jpa or mongodb will be as simple as switching imported jar dependencies - but at least you minimize the impact by using same dao api.
-
you need a fast, simple jdbc wrapper library. jpa or even is an overkill
-
you want to have full control over generated sql if needed
-
you want to work with objects, but don't need lazy loading, relationship handling, multi-level caching, dirty checking... you need and not much more
-
you want to by
-
you are already using spring or maybe even , but still feel like there is too much manual work
-
you have very few database tables
for more examples and working code don't forget to examine .
maven coordinates:
com.nurkiewicz.jdbcrepository
jdbcrepository
0.4
this project is available under maven central repository.
alternatively you can .
in order to start your project must have datasource
bean present and transaction management enabled. here is a minimal mysql configuration:
@enabletransactionmanagement
@configuration
public class minimalconfig {
@bean
public platformtransactionmanager transactionmanager() {
return new datasourcetransactionmanager(datasource());
}
@bean
public datasource datasource() {
mysqlconnectionpooldatasource ds = new mysqlconnectionpooldatasource();
ds.setuser("user");
ds.setpassword("secret");
ds.setdatabasename("db_name");
return ds;
}
}
say you have a following database table with auto-generated key (mysql syntax):
create table comments (
id int auto_increment,
user_name varchar(256),
contents varchar(1000),
created_time timestamp not null,
primary key (id)
);
first you need to create domain object mapping to that table (just like in any other orm):
public class comment implements persistable {
private integer id;
private string username;
private string contents;
private date createdtime;
@override
public integer getid() {
return id;
}
@override
public boolean isnew() {
return id == null;
}
//getters/setters/constructors/...
}
apart from standard java boilerplate you should notice implementing where integer
is the type of primary key. persistable
is an interface coming from spring data project and it's the only requirement we place on your domain object.
finally we are ready to create our dao:
@repository
public class commentrepository extends jdbcrepository {
public commentrepository() {
super(row_mapper, row_unmapper, "comments");
}
public static final rowmapper row_mapper = //see below
private static final rowunmapper row_unmapper = //see below
@override
protected s postcreate(s entity, number generatedid) {
entity.setid(generatedid.intvalue());
return entity;
}
}
first of all we use annotation to mark dao bean. it enables persistence exception translation. also such annotated beans are discovered by classpath scanning.
as you can see we extend jdbcrepository
which is the central class of this library, providing implementations of all pagingandsortingrepository
methods. its constructor has three required dependencies: rowmapper
, and table name. you may also provide id column name, otherwise default "id"
is used.
if you ever used jdbctemplate
from spring, you should be familiar with interface. we need to somehow extract columns from resultset
into an object. after all we don't want to work with raw jdbc results. it's quite straightforward:
public static final rowmapper row_mapper = new rowmapper() {
@override
public comment maprow(resultset rs, int rownum) throws sqlexception {
return new comment(
rs.getint("id"),
rs.getstring("user_name"),
rs.getstring("contents"),
rs.gettimestamp("created_time")
);
}
};
rowunmapper
comes from this library and it's essentially the opposite of rowmapper
: takes an object and turns it into a map
. this map is later used by the library to construct sql create
/update
queries:
private static final rowunmapper row_unmapper = new rowunmapper() {
@override
public map mapcolumns(comment comment) {
map mapping = new linkedhashmap();
mapping.put("id", comment.getid());
mapping.put("user_name", comment.getusername());
mapping.put("contents", comment.getcontents());
mapping.put("created_time", new java.sql.timestamp(comment.getcreatedtime().gettime()));
return mapping;
}
};
if you never update your database table (just reading some reference data inserted elsewhere) you may skip rowunmapper
parameter or use .
last piece of the puzzle is the postcreate()
callback method which is called after an object was inserted. you can use it to retrieve generated primary key and update your domain object (or return new one if your domain objects are immutable). if you don't need it, just don't override postcreate()
.
check out for a working code based on this example.
by now you might have a feeling that, compared to jpa or hibernate, there is quite a lot of manual work. however various jpa implementations and other orm frameworks are notoriously known for introducing significant overhead and manifesting some learning curve. this tiny library intentionally leaves some responsibilities to the user in order to avoid complex mappings, reflection, annotations... all the implicitness that is not always desired.
this project is not intending to replace mature and stable orm frameworks. instead it tries to fill in a niche between raw jdbc and orm where simplicity and low overhead are key features.
in this example we'll see how entities with user-defined primary keys are handled. let's start from database model:
create table users (
user_name varchar(255),
date_of_birth timestamp not null,
enabled bit(1) not null,
primary key (user_name)
);
...and domain model:
public class user implements persistable {
private transient boolean persisted;
private string username;
private date dateofbirth;
private boolean enabled;
@override
public string getid() {
return username;
}
@override
public boolean isnew() {
return !persisted;
}
public void setpersisted(boolean persisted) {
this.persisted = persisted;
}
//getters/setters/constructors/...
}
notice that special persisted
transient flag was added. contract of [crudrepository.save()
]() from spring data project requires that an entity knows whether it was already saved or not (isnew()
) method - there are no separate create()
and update()
methods. implementing isnew()
is simple for auto-generated keys (see comment
above) but in this case we need an extra transient field. if you hate this workaround and you only insert data and never update, you'll get away with return true
all the time from isnew()
.
and finally our dao, bean:
@repository
public class userrepository extends jdbcrepository {
public userrepository() {
super(row_mapper, row_unmapper, "users", "user_name");
}
public static final rowmapper row_mapper = //...
public static final rowunmapper row_unmapper = //...
@override
protected s postupdate(s entity) {
entity.setpersisted(true);
return entity;
}
@override
protected s postcreate(s entity, number generatedid) {
entity.setpersisted(true);
return entity;
}
}
"users"
and "user_name"
parameters designate table name and primary key column name. i'll leave the details of mapper and unmapper (see ). but please notice postupdate()
and postcreate()
methods. they ensure that once object was persisted, persisted
flag is set so that subsequent calls to save()
will update existing entity rather than trying to reinsert it.
check out for a working code based on this example.
we also support compound primary keys (primary keys consisting of several columns). take this table as an example:
create table boarding_pass (
flight_no varchar(8) not null,
seq_no int not null,
passenger varchar(1000),
seat char(3),
primary key (flight_no, seq_no)
);
i would like you to notice the type of primary key in persistable
:
public class boardingpass implements persistable
unfortunately library does not support small, immutable value classes encapsulating all id values in one object (like jpa does with ), so you have to live with object[]
array. defining dao class is similar to what we've already seen:
public class boardingpassrepository extends jdbcrepository {
public boardingpassrepository() {
this("boarding_pass");
}
public boardingpassrepository(string tablename) {
super(mapper, unmapper, new tabledescription(tablename, null, "flight_no", "seq_no")
);
}
public static final rowmapper row_mapper = //...
public static final rowunmapper unmapper = //...
}
two things to notice: we extend jdbcrepository
and we provide two id column names just as expected: "flight_no", "seq_no"
. we query such dao by providing both flight_no
and seq_no
(necessarily in that order) values wrapped by object[]
:
boardingpass pass = boardingpassrepository.findone(new object[] {"foo-1022", 42});
no doubts, this is cumbersome in practice, so we provide tiny helper method which you can statically import:
import static com.nurkiewicz.jdbcrepository.jdbcrepository.pk;
//...
boardingpass foundflight = boardingpassrepository.findone(pk("foo-1022", 42));
check out for a working code based on this example.
this library is completely orthogonal to transaction management. every method of each repository requires running transaction and it's up to you to set it up. typically you would place @transactional
on service layer (calling dao beans). i don't recommend .
spring data jdbc repository library is not providing any caching abstraction or support. however adding @cacheable
layer on top of your daos or services using is quite straightforward. see also: .
..are always welcome. don't hesitate to and .
this library is continuously tested using travis (). test suite consists of 60 distinct tests each run against 8 different databases: mysql, postgresql, h2, hsqldb and derby ms sql server and oracle tests not run as part of ci.
when filling or submitting new features please try including supporting test cases. each is automatically tested on a separate branch.
after forking the building is as simple as running:
$ mvn install
you'll notice plenty of exceptions during junit test execution. this is normal. some of the tests run against mysql and postgresql available only on travis ci server. when these database servers are unavailable, whole test is simply skipped:
results :
tests run: 484, failures: 0, errors: 0, skipped: 295
exception stack traces come from root .
library consists of only a handful of classes, highlighted in the diagram below ():
is the most important class that implements all methods. each user repository has to extend this class. also each such repository must at least implement and (only if you want to modify table data).
sql generation is delegated to . and are provided for databases that don't work with standard generator.
- repackaged:
com.blogspot.nurkiewicz
-> com.nurkiewicz
- first version available in maven central repository
- upgraded spring data commons 1.6.1 -> 1.8.0
- upgraded spring dependencies: 3.2.1 -> 3.2.4 and 1.5.0 -> 1.6.1
- fixed
- oracle 10g / 11g support (see )
- upgrading spring dependency to 3.2.1.release and to 1.5.0.release (see ).
- ms sql server 2008/2012 support (see )
this project is released under version 2.0 of the (same as ).