DAO pattern datasource connection help

After researching and attempting to implement the Data Access Object pattern using the Abstract Factory pattern I run into one problem for which I haven't found a solution.
All of the solutions that I have found hardcode the database connection URL and user credentials into either the concrete DAO factory or the concrete DAO object iteself. However, in the application that I am working with, the user credentials will be entered on a login screen and passed into the business objects that reference the data access objects.
My questions are:
Which object should receive the user credentials and datasource URL to authorize the user? (The storage solution that I am using returns query results based on the user's security settings in the repository.)
How do I abstract this connection information to ensure that if I swap in a different storage solution I won't have to change the business objects or the interface to the DAO factory/objects?

Ideally, one should always use the concrete DAOFactory to get you the database specific connection. The reason being that the one concrete DAOFactory exist for one particular database, and creates/returns DAO objects specialized for firing SQLs to that database.
So writing connection code should be removed from DAO classes and put in the factory class.
Now, coming to your problem.
The user credentials are supplied by the user. These credentials are passed on to your business objects that in turn invoke an operation on a particular DAO to fire a SQL and get back the ResultSet.
The business objects would typically get hold of the AbstractFactory to get the concrete factory, and using the concrete factory handle, it would get the concrete DAO class.
The DAO class in turn would use the concrete DAOFactory to get a connection, fire SQL, get the ResultSet and close/return the connection.
So, the best place to handle your issue is to write a public static final method in your AbstractDAOFactory class that returns you a 'fully configured' concrete DAOFactory class. The right time to use your user supplied credentials is when the AbstractFactory is creating your concrete DAOFactory class.
Why?
Because, every new user would represent a new database connection to your database. And that new user is allowed to do host of things using the number of DAOs that you have. So, ideally, for every user the JDBC connection setup part should be re-configured.
So, just have the AbstractFactory return you a re-configured concrete DAOFactory for every new user by passing this AbstractFactory 2 information:
1. "whichDAOFactory" to return, and
2. "ConfigVO" ValueObject having the UID/PWD.
So extending the example given by Sun:
public static DAOFactory getDAOFactory(int whichFactory, Object ConfigVO)
switch (whichFactory)
case CLOUDSCAPE:
return new CloudscapeDAOFactory().configure(ConfigVO);
So, just by adding an abstract method configure() in the AbstractDAOFactory class to force all the extending concrete class to define their own ways to configure themselve with the user supplied credentials.
Regards

Similar Messages

  • DAO pattern & Lookup datasource with NamingException in the same J2EE APP

    Hello Experts:
    I'm developing an J2EE application with EJB's for transactional operations (that works fine!) and I'm implementing the J2EE DAO Pattern using a DAO ConnectionFactory with OpenSQL/JDBC standard for Querying the DB, but here my problems begins:
    The DAOConnectionFactory Singleton Class is placed in a java package inside the same application that holds my Entitys & Sessions (remember this ejb's works fine!) and I'm trying to get the "localy-configured-in-the-j2ee-application" alias-datasource for my DAO Querys, but "lookup" doesn't find this resource!!!.
    I'm thinking, there's not remote access to this resouce because the DAO-CF is in the same context and JVM, but this appreciation is correct? or  what I miss?
    Another remark: I've been used the Telnet Administrator and the same lookup string is founded correctly!.
    Here is the Codec:
    public class ConexionFactory implements Serializable {
         private static ConexionFactory singleton = null;
         private DataSource ds;
         protected ConexionFactory() {
              String source = "jdbc/BURO_COMM";
              try {
                   Context ctx = new InitialContext();
                   ds = (DataSource) ctx.lookup(source);
                   if (null == ds) {
                        throw new RuntimeException("Couldn't get the datasource");
              } catch (NameNotFoundException e) {
                   throw new RuntimeException(e.getMessage());
              } catch (NamingException e) {
                   throw new RuntimeException(e.getMessage());
         public static ConexionFactory getInstance() {
              if (null == singleton) {
                   singleton = new ConexionFactory();
              return singleton;
    .... (some other methods)

    Hello all again:
    I've been making some tests (and investigation reading other posts) and I found that everything is related with the Resource Sharing Scope of my Session Object that commands the process. And it works fine.
    By now, for my conceptual test is Ok and finally i must work in this app arquitecure path:
    ->Web Service (with a POJO in a web module)
    >ProcessRender Class (a POJO with the main control logic)
    >BussinesDelegate's -->ServiceLocator
    >SessionFacades --->Entity's
    >DAO Connection Factory---->OpenSQL/JDBC Querys

  • Help on DAO pattern

    Hello!
    I'm having a problem implementing the DAO pattern.
    Suppose that I have two database tables:
    emp(id, name, sex, deptid)
    dept(id, name)
    If I follow the DAO pattern, I use two DAO interfaces, one for each
    table, and "entity". EmployeeDAO, and DepartmentDAO.
    (I'm using an abstract factory to create storage-specific DAOS)
    These DAOs return instances of Employee, and Department, or lists of them. (ValueObjects).
    This is all great and works very well, but suppose I want to produce the following
    presentation on the web:
    deptname | male | female
    Dept A   | 10   | 20
    Dept B   | 15   | 30In essense, this is a request for all the departments.
    I would iterate through this list, and want to display how many
    males, and how many females there are in each department.
    Should this be in the DepartmentDAO, or in a separate DAO?
    Or should this be put in some BusinessDelegate?
    That is, DepartmentDelegate.countMales(dept);
    Or should I put a method in the ValueObject Department that in turn uses the DAO to count males?
    Or should I load the number of females into the valueobject when fetching it from the
    database in the first place?
    Or should I construct a specialized view of the department such as:
    class StupidViewOfDepartment
       private Department dept;
       private int males;
       private int females;
       public StupidViewOfDepartment(Department dept, int males, int females){
       public int numFemales();
          return females;
       public int numMales(){
          return males;
    }...having some class return a collection of this specialized view?
    In that case, which class would that be?
    A new DAO or the DepartmentDAO?
    All classical examples of DAO patterns that I can find, fails to adress
    other issues than just retreiving a single Employee, or a list of them.
    Can someone advise me on this?

    You said:
    My problem might be, that the data I'm asking for, is not distinct objects, business objects,
    but a "new type of object" consisting of this particular information, that is
    deptname, numMales, numFemales.
    EXACTLY! You are querying for data that is either aggregate, a combination of various other business objects or a very large set of known business objects. In any of these cases, you probably don't want to use a vanilla DAO. Write a dedicated search DAO. Depending on your OO purity level and time horizon, you could make VO's for the search request or the results returned.
    You said:
    I'd like to think of this as report functionality, or aggregate reports.
    I'm good at database programming, and I'm particularly good at optimization,
    so if I cannot do this the good-looking way, I can always resort to brutal techniques...ehum
    PERFECT! If you are great at database operations, and you know exactly how you want to optimize a given search, then give it its own DAO. The main problem with the object->relational boundary is that most cookie-cutter solutions (ala entity beans with CMP) cannot even remotely appropach the optimization level of a good database programmer. If you want to optimize a search in SQL or a stored procuedure, do that. Then have a dedicated search DAO use that funcitonality. (If you want to do it "right", make a search Factory object that will return various implementations, some may be vendor-specific or optimized, others might be generic; the Factory simply returns a search DAO interface, while specific implementations can concentrate on the task at hand. Swapping implementations with the same interface should be trivial).
    - Saish
    "My karma ran over your dogma." - Anon

  • Loosing datasource connection in a server thread

    Hi,
    In a backing bean I start a long term thread that uses the datasource connection taken from application module.
    Everything works fine but after a period of time between one and two hours the connection is lost and server throws a
    <BEA-001112> <Test "SELECT 1 FROM DUAL" set up for pool "AEE2010DS" failed with exception: "java.sql.SQLException: Connection Closed".>
    Is there any way to stop the server from closing the connection that is used in a separate thread, programmatically or using configuration?
    Any comment will be helpful,
    Thanks

    That looks like something external is killing the connection, either the DBMS or a firewall.

  • Error !! Cannot fetch a datasource connection

    I am a beginner in Oracle BPEL process Manager,
    i am experiencing the following error :
    After starting the BPEL PM server, i got the following in the Dos Window:
    " Message Handle error:
    An exception occurred while attempting to process the message "com.collaxa.cube.engine.dispatch.message.process.SetDbDefaultMessage."the exception is tranaction was rolledback........"
    then i tried also to open the BPEL console and i logged in , but i got
    "Cannot fetch a datasource connectionThe process domain was unable to establish a connection with the datasource with the connection URL "jdbc/BPELServerDataSource". The exception reported is: Internal Error:Invalid Connect String
    Please check that the machine hosting the datasource is physically connected to the network. Otherwise, check that the datasource connection parameters (user/password) is currently valid."
    What could be wrong !
    Please Help.
    Thanks in advance

    Hey Rana,
    in OC4J_BPEL container, that is located under $AS_HOME/j2ee go to the config directory and open data-sources.xml.
    it seems during installation you might have provided wrong information..
    could you pls paste it here, that we can figure out what's wrong..
    in what enviroment did this occur,
    thx clemens

  • DAO Pattern and the ServiceLocator

    I have been developing a lightweight framework for working with AIR and the SQL API. This framework has no dependencies on Cairngorm however it is built around a typical DAO implementation.
    While developing this I considered how it should be integrated with Cairngorm, which lead me to wonder if a simple DAO marker interface which could be retrieved from the ServiceLocator (and cast to the correct abstraction by a business delegate) would not be all that is needed to have a rather flexible service layer in Cairngorm?
    For example, consider the following pseudo code which is what I would imagine a business delegate to look like:
    class FooDelegate {
    protected fooDAO:IFooDAO;
    public FooDelegate(responder:IResponder) {
    fooDAO = ServiceLocator.getinstance().getDAO(Service.FOODAO) as IFooDAO;
    fooDAO.addResponder( responder );
    public getFoo() void {
    fooDAO.getFoo();
    public addFoo(foo:IFoo) {
    fooDAO.addFoo(foo);
    public deleteFoo(foo:IFoo) {
    fooDAO.deleteFoo(foo);
    As you can see the delegate would cast the dao to the correct abstraction and then just wrap the DAOs API (somewhat similar to an Assembler in LCDS).
    A custom DAO interface would extend the DAO marker interface so that the ServiceLocator could find it:
    interface IFooDAO extends IDAO
    getFoo() void;
    addFoo(foo:IFoo);
    deleteFoo(foo:IFoo);
    Service.mxml would define an instance of the dao as an abstraction and then call a factory to get the appropriate implementation:
    public fooDAO:IFooDAO = DAOFactory.getDAO("foo");
    I see much potential in this type of implementation as it would allow services to be swaped out with different implementations via a config or with an IoC implementation etc, thus allowing the services themselves to be completely transparent to client code.
    I wanted to see if anyone had any thoughts on this as well?
    Best,
    Eric

    Thanks, duffymo, that makes sense. However ... having read through numerous threads in which you voice your opinion of the DAO World According to Sun, I'd be interested to know your thoughts on the following ...
    Basically, I'm in the process of proposing an enterprise system architecture, which will use DAO as the primary persistence abstraction, and DAO + JPA in the particular case of persistence to a RDBMS. In doing so, I'd like to illustrate the various elements of the DAO pattern, a la the standard class diagram that relates BusinessObject / DataAccessObject / DataSource / TransferObject (http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html). With reference to this model, I know that you have a view on the concept of TransferObject (aka ValueObject?) - how would you depict the DAO pattern in its most generic form? Or is the concept of a generic DAO pattern compromised by the specific implementation that is used (in this case JPA)?

  • Questions about DAO pattern

    Hi,
    I am a junior programmer and I am trying to understand somewhat more about best practices and design patterns.
    I am looking for more information regarding the DAO pattern, not the easy examples you find everywhere on the internet, but actual implementations of real world examples.
    Questions:
    1) Does a DAO always map with a single table in the database?
    2) Does a DAO contain any validation logic or is all validation logic contained in the Business Object?
    3) In a database I have 2 tables: Person and Address. As far as I understand the DAO pattern, I now create a PersonDAO and an AddressDAO who will perform the CRUD operations for the Person and Address objects. PersonDAO only has access to the Person table and AddressDAO only has access to the Address table. This seems correct to me, but what if I must be able to look up all persons who live in the same city? What if I also want to look up persons via their telephone numbers? I could add a findPersonByCity and findPersonByTelephoneNumber method to the PersonDAO, but that would result in the PersonDAO also accessing the Address table in the database (even though there already is an AddressDAO). Is that permitted? And why?
    I hope someone can help me out.
    Thanks for your time!
    Jeroen

    That is exactly what I am trying to do. I am writing it all myself to get a better understanding of it.
    Please bear with me, because there are some things I dont understand in your previous answer.
    1) Each BO validates his corresponding DTO and exposes operations to persist that DTO. Each DTO will be persisted in the database via his corresponding DAO. So this would be:
    - in PersonBO
    public void save(PersonDTO personDTO) {
    this.validate(personDTO); // does not validate the nested address DTOs
    this.personDAO.save(personDTO); // does not save the nested address DTOs
    - in AddressBO
    public void save(AddressDTO addressDTO) {
    this.validate(addressDTO);
    this.addressDAO.save(addressDTO);
    Am I viewing it from the right side now?
    2) Imagine a form designed to insert a new person in the database, it contains all fields for the Person DTO and 2 Address DTOs.
    How would I do this using my Business Objects?
    This is how I see it:
    // fill the DTOs
    daoManager.beginTransaction();
    try {
    personBO.setDao(daoManager.getDao(PersonDAO.class));
    personBO.save(personDTO); // save 1
    addressBO.setDao(daoManager.getDao(AddressDAO.class));
    addressBO.save(personDTO.getAddress(1)); // save 2
    addressBO.save(personDTO.getAddress(2)); // save 3
    daoManager.commit();
    catch(Exception e) {
    daoManager.rollBack();
    If I insert the transaction management inside the DAOs, I can never rollback save 1 when save 2 or save 3 fail.
    It can be that I am viewing it all wrong, please correct me if that is the case.
    Thanks!
    Jeroen

  • Hibernate, DAO pattern and tree hierarchy

    Hi all,
    I use Hibernate for a short period of time and now I'm facing a complex problem . I try figure it out what is the best practice for the following scenario:
    I have the following classes: Department, Team, Position, all of them inherited from a Entity class even there is almost no difference between them. But I wanted different classes for different entities.
    I try to create a tree hierachy, each object is with all others in a bidirectional one-to-many relationship. For example a Department can have Teams and Positions as children and a Position can have Departments and Teams as children.
    I created the mapping files and I don't know how to create all necessary methods without duplicating the code.
    Questions:
    1. Do I need a DAO pattern implemented for this design?
    2. Can you recomend some documentation or ideas that will help me find out what is the best approach in this case?
    Thanks

    Write the DAO for the class that is the root of the tree. Sounds like it should be DepartmentDao.
    I don't know of much better documentation than the Hibernate docs. Check their forum, too.
    %

  • How to implement DAO pattern in CMP

    How do I use the DAO pattern when going for container managed persistence, because all the database access is defined by the CMP.
    How to go about it ?

    Hi,
    The DAO pattern http://java.sun.com/blueprints/patterns/DAO.html
    is used with Bean Managed Persitence(BMP). For CMP you should not write the SQL in the EJB code, but instead let the container generate the SQL and handle all the data access.
    Another pattern that might help when modelling your EJBs is the Composite Entity pattern at
    http://java.sun.com/blueprints/patterns/CompositeEntity.html
    Also, the new J2EE BluePrints book has some tips and strategies in the EJB tier chapter at
    http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/index.html
    hope that helps,
    Sean

  • More information in DAO pattern

    Could u send me the document more detail about DAO in Petstore
    I have error when I customize Petstore:
    I replace searchItems function with searchFullDocument But I have error as follows:
    javax.servlet.ServletException: An error occurred while evaluating custom action attribute "value" with value "${catalog.searchFullDocument}": An error occurred while getting property "searchFullDocument" from an instance of class docman.catalog.client.CatalogHelper
         at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:471)
         at jasper.simpleCatalog_jsp._jspService(_simpleCatalog_jsp.java:489)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.iplanet.ias.web.jsp.JspServlet$JspServletWrapper.service(JspServlet.java:552)
         at com.iplanet.ias.web.jsp.JspServlet.serviceJspFile(JspServlet.java:368)
         at com.iplanet.ias.web.jsp.JspServlet.service(JspServlet.java:287)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.StandardWrapperValve.invokeServletService(StandardWrapperValve.java:720)
         at org.apache.catalina.core.StandardWrapperValve.access$000(StandardWrapperValve.java:118)
         at org.apache.catalina.core.StandardWrapperValve$1.run(StandardWrapperValve.java:278)
         at java.security.AccessController.doPrivileged(Native Method)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:274)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:212)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:203)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
         at com.iplanet.ias.web.connector.nsapi.NSAPIProcessor.process(NSAPIProcessor.java:157)
         at com.iplanet.ias.web.WebContainer.service(WebContainer.java:598)
    Root Cause
    javax.servlet.jsp.JspException: An error occurred while evaluating custom action attribute "value" with value "${catalog.searchFullDocument}": An error occurred while getting property "searchFullDocument" from an instance of class docman.catalog.client.CatalogHelper
         at org.apache.taglibs.standard.lang.jstl.Evaluator.evaluate(Evaluator.java:146)
         at org.apache.taglibs.standard.lang.jstl.Evaluator.evaluate(Evaluator.java:165)
         at org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager.evaluate(ExpressionEvaluatorManager.java:112)
         at org.apache.taglibs.standard.tag.el.core.ExpressionUtil.evalNotNull(ExpressionUtil.java:85)
         at org.apache.taglibs.standard.tag.el.core.SetTag.evaluateExpressions(SetTag.java:147)
         at org.apache.taglibs.standard.tag.el.core.SetTag.doStartTag(SetTag.java:95)
         at jasper.simpleCatalog_jsp._jspService(_simpleCatalog_jsp.java:384)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.iplanet.ias.web.jsp.JspServlet$JspServletWrapper.service(JspServlet.java:552)
         at com.iplanet.ias.web.jsp.JspServlet.serviceJspFile(JspServlet.java:368)
         at com.iplanet.ias.web.jsp.JspServlet.service(JspServlet.java:287)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.StandardWrapperValve.invokeServletService(StandardWrapperValve.java:720)
         at org.apache.catalina.core.StandardWrapperValve.access$000(StandardWrapperValve.java:118)
         at org.apache.catalina.core.StandardWrapperValve$1.run(StandardWrapperValve.java:278)
         at java.security.AccessController.doPrivileged(Native Method)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:274)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:212)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:203)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:505)
         at com.iplanet.ias.web.connector.nsapi.NSAPIProcessor.process(NSAPIProcessor.java:157)
         at com.iplanet.ias.web.WebContainer.service(WebContainer.java:598)

    Hi,
    You can get more info on the DAO pattern at http://java.sun.com/blueprints/patterns/DAO.html
    and also some implementation details of the petstore are descibed at http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/sample-app/sample-app1.3.1.html
    Also, you might want to ask this kind of question at
    http://archives.java.sun.com/archives/j2eeblueprints-interest.html
    hope that helps,
    Sean

  • DAO pattern and Java Persistence API

    Hi
    This is a question for anyone who might be familiar with the standard DAO design pattern and the Java Persistence API (JPA - part of EJB3). I'm new to this technology, so apologies for any terminology aberrations.
    I am developing the overall architecture for an enterprise system. I intend to use the DAO pattern as the conceptual basis for all data access - this data will reside in a number of forms (e.g. RDBMS, flat file). In the specific case of the RDBMS, I intend to use JPA. My understanding of JPA is that it does/can support the DAO concept, but I'm struggling to get my head around how the two ideas (can be made to) relate to each other.
    For example, the DAO pattern is all about how business objects, data access objects, data transfer objects, data sources, etc relate to each other; JPA is all about entities and persistence units/contexts relate to each other. Further, JPA uses ORM, which is not a DAO concept.
    So, to summarise - can DAO and JPA work together and if so how?
    Thanks
    P.S. Please let me know if you think this topic would be more visible in another forum (e.g. EJB).

    Thanks, duffymo, that makes sense. However ... having read through numerous threads in which you voice your opinion of the DAO World According to Sun, I'd be interested to know your thoughts on the following ...
    Basically, I'm in the process of proposing an enterprise system architecture, which will use DAO as the primary persistence abstraction, and DAO + JPA in the particular case of persistence to a RDBMS. In doing so, I'd like to illustrate the various elements of the DAO pattern, a la the standard class diagram that relates BusinessObject / DataAccessObject / DataSource / TransferObject (http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html). With reference to this model, I know that you have a view on the concept of TransferObject (aka ValueObject?) - how would you depict the DAO pattern in its most generic form? Or is the concept of a generic DAO pattern compromised by the specific implementation that is used (in this case JPA)?

  • Infosource and datasource connection

    Hi Experts,
    In the BI 3.5 business content, what is the best way to decide which datasource connects to which infosource? For example if i were to install BI content for SD i have about 8 datasources and 20 infosources and 6 cubes only.
    How can i setup a dataflow based on Bi content only?
    Should i make a decision based on the fields i am interested in? Please educate me on this.
    Thanks
    K

    Hi Krishna,
    Go to RSA1--->, right mouse show data flow you can double click the elements.
    On the Source systems you can see the relation between DS and IS.
    Also try table RSOLTPSOURCE - field OLTPSOURCE for datasource,field BASOSOURCE for infosource.using 'show data flow' as mentioned, click 'technical name on/off' to have the technical name displayed.
    hope this helps.
    Regards
    CSM Reddy

  • How to remove unused datasource connections in Report Builder 3

    In Report Builder 3.0 using a wizard to create a new Report, select create a DataSet. It opens a "Choose a connection to a datasource" dialog box. It shows previously used datasource connections of other ReportSevers I have accessed long
    time back. But I dont want to see datasource connection not in use. How can I remove those datasource connections used in past but they are still available in the list.  

    Hi Saty
    You can find more information about Remove previously used datasource connections.
    http://connect.microsoft.com/SQLServer/feedback/details/679232/cannot-remove-old-unusable-data-source-connections-from-report-builder-3-0-wizard-dialog
    SUHAS http://suhaskudekar.blogspot.com/ Please click "Mark as Answer" if this resolves your problem or "Vote as Helpful" if you find it helpful.

  • Is dao pattern is the best practice in projects

    let me know if dao pattern is the best followed in all almost all the
    projects though finding alternatives to it. please clarify this for me and also i do want to know the best practices of the industry in using design patterns.

    There is no 'best' pattern. It is just all abouthow
    and where to apply them. This is very true,but these are common
    design patterns used in industry for standard
    problems.
    ost of the time patterns are used not for some
    special reason but for more manageability and ease of
    change.So if you have a small application than it's
    ok but if you are working on big application which
    are needed to be maintained over a time and changes
    are frequent.Than its better to start learning about
    patterns because their will be problems which right
    now you can't see but eventually you have to take
    care of.That is either incorrect or phrased poorly.
    Patterns come about because someone analyzes different existing code bases and notes that there are similarities in the way they are built.
    It isn't that they are easier to maintain but rather that because the pattern has similarities it is easier to comprehend, understand the limitations, understand the possible related patterns, etc. That might lead to easier maintainance but it isn't the reason. The reason is because, if and only if, the requirements/architecture lead to a situation where that pattern could be properly used.

  • Datasources connection questions

    hi all
    my question is about How the connections stored in a Jndi server datasource pool are managed.
    For example, I'm developing a J2EE application with Ejbs and Datasources, etc. I saw that when I want to retrieve a connection from datasource to work on it I need do something like this:
    For example to retrieve a datasource connection:
    Hashtable jndiProps = new Hashtable();
    jndiProps.put(Context.INITIAL_CONTEXT_FACTORY,...);
    jndiProps.put(Context.PROVIDER_URL, ...);
    Context context = new InitialContext(jndiProps);
    DataSource ds = (DataSource) context.lookup("jdbc/MyDatasource");
    Connection con = ds.getConnection();
    ...I know in this case that the server manages a datasource connection pool, etc
    My question is when a get a connection from the Datasource pool of my app server. do I need to release the connection with some special method when I finish with it (in order to return it to the pool) or it doesn't matter ?
    thanks in advance

    If I have three prepared statements right in a row with nothing in between should I close the connection after each one and then get it again?
    Seems like I would be just as well off to just get the conn once do the 3 things then close it.
    and in spots I might actually be doing something as i step through the first result set so can i use conn.preparedStatement() in the loop many times without getting the connection and closing each time through the loop?
    i of course close all PS and RS and use diff PS2 and RS2 in the loop so i 'm just talking about keeping the conn open while (RS.next()) and use it multiple times to conn.preparedStatement() inside the loop?
    or should i use 2 connections lol and open conn1 and then in loop use conn2 and close it each time around the loop and then close conn1 when i exit the loop?

Maybe you are looking for