Is it possible to reuse a JDBI DAO instance?

final MyDAO dao = database.onDemand(MyDAO.class); 

Can dao instances be used? Or do we need to create an instance for each use?

From the code, it looks like it is responsible for maintaining the database transaction. However, in the DropWizard examples: -

 final UserDAO dao = jdbi.onDemand(UserDAO.class); environment.jersey().register(new UserResource(dao)); 

So, in the same resource, this dao instance will be reused on all paths. This means that when two requests are made for the same resource (possibly in two ways), they will both use the same dao instance. It's not a problem?

+5
source share
1 answer

onDemand will automatically receive and release the connection as necessary. Typically, this means that he will receive a connection to execute the instruction, and then immediately issue it, but various things, such as open transactions or iterator-based results, will cause the connection to remain open until the transaction will end or the result of the repetition will not be completely passed. Therefore, even if two requests access the same resource, they will be in different descriptors. Therefore, this will not cause any problems.

 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 that onDemand Dao creates a new descriptor every time you access the method.

+4
source

Source: https://habr.com/ru/post/1209982/


All Articles