WelcomeTo
WelcomeTo

Reputation: 20591

DAO. JDBC. Where to place Connection object?

Where must be placed Connection object in DAO design pattern?

Do I need to create separate class (e.g. DaoManager) with 2 methods: open() and close()? And in business logic do like:

DaoManager.open();
PersonDao personDao = DaoFactory.getPersonDao();
Person person = personDao.getById(personId);
.... //more DAO operations
DaoManager.close()

Upvotes: 1

Views: 2013

Answers (2)

JB Nizet
JB Nizet

Reputation: 692043

The connection should be a local variable of the PersonDao.getById() method (and of the other DAO methods). It should get the connection from a DataSource, use it, and close it in a finally block.

If you told a bit more about your environment (Spring, EJB container?), I could give more explanations.

Upvotes: 2

Henry
Henry

Reputation: 43778

In a large application you would typically hold the connections in a connection pool so that they can be reused for several purposes. One does this because opening a new DB connection can be somewhat expensive.

The DAO gets a reference to the pool and takes out a connection when it is needed. After the operation it would give it back to the pool.

There are several open source implementations for connection pools available, you may want to reuse one of these.

Upvotes: 1

Related Questions