4.6. Design Guidelines and Patterns

We have added a level of complexity to the example in this chapter by including an Enterprise Java Bean that accesses a database. The Music EJB can be a stateless session bean because it accesses the database in a read-only capacity.

DAO Pattern

Our first implementation keeps things as simple as possible by implementing database calls as private methods inside the bean implementation code. The trade-off between simplicity and lack of flexibility means that our code is “hard wired” to access a particular vendor's database. The second version uses the Data Access Object (DAO) Pattern to solve this lack of flexibility. Our approach is to create an interface that the bean implementation code invokes, and to write at least one implementation class for a particular database vendor. A factory class instantiates the implementation object based on the declarative information inserted into the DAO client's deployment descriptor. The EJB container reads the deployment descriptor and makes this information available to EJB components through the JNDI naming service.

Factory Pattern

The DAO Pattern uses the Factory Pattern for part of its implementation. A factory is responsible for creating objects or families of objects. A factory can also reuse existing objects, if possible. The strategy is that you place the logic for what gets created and how it gets created inside a factory class. The client (who wants to use one of these objects) makes a request to the factory object for instantiation. Our example shows the factory class using the JNDI naming service to acquire the name of the class that it instantiates.

Connection Pooling

One of the services provided by the EJB container is to manage a pool of database connections. Connections are made by invoking the getConnection() method of class javax.sql.DataSource. By acquiring a database connection through the DataSource object, you allow the EJB container to optimize connection pooling and management. It's also a good idea to acquire, use, and release connections before returning to the client. You should hold on to a connection only for as long as you need it.

The Role of finally

Make sure you release all database connections within finally blocks. This ensures that the connection will always be released, even when an exception is thrown. Furthermore, you should release the database connection after closing any JDBC statements and result sets.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.240.80