final MyDAO dao = database.onDemand(MyDAO.class);
Can dao
instances be reused? Or do we need to instantiate it for every use?
From code it looks like it is responsible for maintaining a DB transaction. However, in DropWizard the examples is:-
final UserDAO dao = jdbi.onDemand(UserDAO.class);
environment.jersey().register(new UserResource(dao));
So, in the same resource this instance of dao will be reused at all paths. That means when two requests are made to the same resource (maybe in two paths) then both of them will use the same dao instance. Won't this cause problem?
onDemand will obtain and release connection automatically, as it needs to. Generally this means that it will obtain a connection to execute a statement and then immediately release it, but various things such as open transactions or iterator based results will lead to the connection remaining open until either the transaction completes or the iterated result is fully traversed. So even if when two requests are accessing the same resource, they will be in different handle. So it wont cause any problem.
public abstract class Dao implements GetHandle {
public void printHandle() {
System.out.println(getHandle());
}
}
@Test
public void testHandle() {
Dao onDemandDao = dbi.onDemand(Dao.class);
Handle handle = dbi.open();
Dao handleAttachedDao = handle.attach(Dao.class);
Dao openDao = dbi.open(Dao.class);
for(int i=0; i< 5; i++ ) {
onDemandDao.printHandle();
}
for(int i=0; i< 5; i++ ) {
handleAttachedDao.printHandle();
}
for(int i=0; i< 5; i++ ) {
openDao.printHandle();
}
}
The output for this test is,
org.skife.jdbi.v2.BasicHandle@35d114f4
org.skife.jdbi.v2.BasicHandle@3684d2c0
org.skife.jdbi.v2.BasicHandle@4be460e5
org.skife.jdbi.v2.BasicHandle@454e9d65
org.skife.jdbi.v2.BasicHandle@7805478c
org.skife.jdbi.v2.BasicHandle@6807989e
org.skife.jdbi.v2.BasicHandle@6807989e
org.skife.jdbi.v2.BasicHandle@6807989e
org.skife.jdbi.v2.BasicHandle@6807989e
org.skife.jdbi.v2.BasicHandle@6807989e
org.skife.jdbi.v2.BasicHandle@c2e33
org.skife.jdbi.v2.BasicHandle@c2e33
org.skife.jdbi.v2.BasicHandle@c2e33
org.skife.jdbi.v2.BasicHandle@c2e33
org.skife.jdbi.v2.BasicHandle@c2e33
You can see, onDemand Dao everytime creates new handle when access the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With