EJB design: EJB design + database + jsp
I have a web application (JSP) and i want do do the business on a stateless session EJB.
- Posted by: Claudia Vaz
- Posted on: September 11 2002 09:14 EDT
The business methods need to access to a database multiple times to get some data for the calculations.
My first question is:
- should the connection to the database be made at the time of the creation or activation of the EJB and when we remove or passivate the EJB we close the connection to the database
- should i have a class that connects,shuts down the connection and executes querys to the database and in the remote and bean inteface of the EJB i have business methods that when necessary connect to the databse.
My second question is:
-In the Jsp pages i have some combobox that are filled with information from the database. Should i define the methods to get the information in the EJB or in helper classes of the web application.
My third question is:
-Where should i instantiate the EJB? In the JSP pages or in helper classes of the web application(like a client)?
thanks in advance. Hope somemone helps.
Is there any site or documents that teaches us to structure Java applications?
If you go through the standard J2EE patterns (http://developer.java.sun.com/developer/restricted/patterns/J2EEPatternsAtAGlance.html), you will get answers to all your questions.
Anyway , I will try to briefly answer your questions.
Ans1> It's not a good idea to intermix business logic with data access logic. If you have made up your mind not to use entity bean , the u can call DAOs directly from your session bean , but let the DAOs be responsible for all data acces. See DAO pattern.
Ans2 & Ans3>
Your presentation layer should not be tightly coupled to the business servicess. You can use Business Delegate pattern to reduce tight coupling. The business delegate will be responsible for getting all business services done via a lookup service. Please refer to the "Business Delegate pattern"
If you're using EJBs, it means you've got some application server, right? Then you shouldn't handle database connection creation yourself, but instead use the DataSource(s) provided by the container.
1. the DataSource is looked up from JNDI
2. Connection c = dataSource.getConnection();
3. do something with the connection
The DataSource handles connection pooling behind the scenes, so you don't need to do any extra and you get major performance improvements over creating a new connection per request. (step 4, c.close(), doesn't actually close the connection, but returns the connection back into the pool)