Data Access Object (DAO) pattern

Can anybody provide some real-world implementation examples of the DAO pattern?
I already looked at Sun's Java Petstore. They use DAO only for read-only database queries.
DAO: http://jinx.swiki.net/282

DAO's are basically meant for read only.The other purpose is to develop support for multiple databases in parallel.
1. Interface
public interface UserDAO {
public void attachUserToRole();
2. Class for Oracle
public void attachUserToRole()
//provide implementation here
3. Class for SQLserver
public class UserMSSqlDAOImpl extends MSSqlDAO implements UserDAO {
public void attachUserToRole()
//provide implementation here
4. Class for any other database u wish
5. DAO Factory
public class UserDAOFactory {
public static UserDAO getDAO() {
int daoType = DatabaseTypes.getInstance().getDatabaseType();
if (daoType == DatabaseTypes.ORACLE)
return (UserDAO) new UserOracleDAOImpl();
if (daoType == DatabaseTypes.MS_SQL)
return (UserDAO) new UserMSSqlDAOImpl();
return null;

Similar Messages

  • Impleneting Data Access Object(DAO)

    Hi Guys...
    I have one doubt. needs help from u ppl.
    Suppose there r 5-6 tables, so its certainly not a good idea to code as much number of Entity Beans. What i have read is, make one Entity Bean n then make others as DAO(Data Access Objects) and map the DAOs with the table. I don't understand how to do that..:-( could anyone of u plz explain it.
    On a high level i just want to know that how introduction of DAO reduces the number of Entity Beans???
    I have read books(Design Patterens from wrox publication), i know wat DAO is, but unable to understand the logic which i have mentioned above.
    Any sample code will definitely be of gr8 help.
    Thanx in Advace.
    Jam

    Hi Jam,
    Assuming you haven't already read it, perhaps this will help you:
    http://java.sun.com/blueprints/patterns/DAO.html
    You can also find relevant information from this Web site
    [Again, I am assuming that you have not visited it, yet.]
    http://www.theserverside.com
    Hope this helps.
    Good Luck,
    Avi.

  • Data Access Object for Data Warehouse?

    Hi,
    Does anyone know how the DAO pattern looks like when it is used for a data warehouse rather than a normal transactional database?
    Normally we have something like CustomerDAO or ProductDAO in the DAO pattern, but for data warehouse applications, JOINs are used and multiple tables are queried, for example, a query may contains data from the Customer, Product and Time table, what should the DAO class be named? CustomerProductTimeDAO?? Any difference in other parts of the pattern?
    Thanks in advance.
    SK

    In my opinion, there are no differences in the Data Access Object design pattern which have any thing to do with any characteristic of its implementation or the storage format of the data the pattern is designed to function with.
    The core pupose of the DAO design pattern is to encapsulate data access code and separate it from the business logic code of the application. A DAO implementation might vary from application to application. The design pattern does not specify any implementation details. A DAO implementation can be applied to group of XML data files, an Excel-based CSV file, a relational database, or an OS file system. The design is the same for all these, it is the implementation that varies.
    The core difference between an operational database and a strategic data warehouse is the purpose of why and how the data is used. It is not so much a technical difference. The relational design may vary however, there may be more tables amd ternary relationships in a data warehouse to support more fine-tuned queries; there may be less tables in a operational database to support insert/add efficiencies.
    The DAO implementation for a data warehouse would be based on the model of the databases. However the tables are set up, that is how the DAO is coded.

  • Data Access Object

    hi everyone,
    i want to basic information of Data Access Object(DAO).
    i.e. what is it?
    how to use it?
    thanks

    what it is:
    http://en.wikipedia.org/wiki/Data_Access_Object
    how to use it:
    just like any other pattern. You can check the web for examples

  • Data Access Objects : JDBC Driver Not Found

    Hi,
    I am having a strange problem accessing JDBC Driver ( for Informix Database, if this
    information helps )
    I am using Data Access Objects ( DAOs ) to fetch multiple records.
    The DAO is accessed from Session Bean for this case.
    The constructor of the DAO does the JNDI lookup for the TxDataSource
    and set it to a class attribute of the DAO. This DataSource is pointing
    to a connection pool
    In the getConnection() private method if DAO we use this DataSource
    to pickup a onnection from the pool and fire a sql query.
    This public method say getMultipleRecords( query conditions ) of DAO
    returns a number of macthing records to the Session Bean.
    This approach works fine in general. But sometimes I get an
    java.sql.SQLException
    SQLException ERROR MESSAGE is:
    "Error accessing jdbc driver: driverURL = jdbc:weblogic:pool:myConnPool, props= {enableTwoPhaseCommit=true,
    connectionPoolID=myConnPool}"
    Once this exception occurs every time the method is called the same exception keep
    coming.
    Once I restart the server this API starts working again.
    Could anyone give any reason why this exception might occur.
    Please send an e-mail to [email protected] while replying to this message.
    Thanks in advance
    Gunajit

    Hi Gunajit
    you need to ensure that the connections are properly closed. If you are
    closing the connections properly, increase the number of connections in the
    connection pool.
    hth
    sree
    "Gunajit" <[email protected]> wrote in message
    news:3ce082ca$[email protected]..
    >
    Hi,
    I am having a strange problem accessing JDBC Driver ( for InformixDatabase, if this
    information helps )
    I am using Data Access Objects ( DAOs ) to fetch multiple records.
    The DAO is accessed from Session Bean for this case.
    The constructor of the DAO does the JNDI lookup for the TxDataSource
    and set it to a class attribute of the DAO. This DataSource is pointing
    to a connection pool
    In the getConnection() private method if DAO we use this DataSource
    to pickup a onnection from the pool and fire a sql query.
    This public method say getMultipleRecords( query conditions ) of DAO
    returns a number of macthing records to the Session Bean.
    This approach works fine in general. But sometimes I get an
    java.sql.SQLException
    SQLException ERROR MESSAGE is:
    "Error accessing jdbc driver: driverURL = jdbc:weblogic:pool:myConnPool,props= {enableTwoPhaseCommit=true,
    connectionPoolID=myConnPool}"
    Once this exception occurs every time the method is called the sameexception keep
    coming.
    Once I restart the server this API starts working again.
    Could anyone give any reason why this exception might occur.
    Please send an e-mail to [email protected] while replying to this
    message.
    >
    Thanks in advance
    Gunajit

  • Best Practice Using Data Access Object Pattern

    I was wondering what would be the best approach with regards to implementing the Data Access Object pattern:
    Given the following database tables:
    teacher {teacher_id, teacher_name, ...}
    subject {subject_id, subject_name, ...}
    teacher_subject {teacher_id, subject_id}where teacher and subject hold details on teachers and subjects respectively and teacher_subject links teachers with the subjects that they currently teach, would I be better off:
    1) implementing three distinct DAO classes i.e. TeacherDAO, SubjectDAO, TeacherSubjectDAO, that correspond to each database table;
    2) implementing a single DAO class that controls access to all three tables, given that business operations often rely on access to all three tables e.g. getSubjectTeachers(Subject s), assignSubjectToTeacher(Subject s, Teacher t), getSubjectsTaughtBy(Teacher t)...
    Thanks
    Ian

    ...would I be better off:Depends on the system.
    If you are always going to have a teacher with subjects then all you need is one class.
    If on the other hand sometimes you are going to have subjects with teachers (given that you have a link table a many to many relationship exists) then two DAOs would exist.
    It would be unlikely for you to have a DAO for the link table unless perhaps you are anticipating a teacher having tens of thousands of subjects or one subject having tens of thousands of teachers.

  • Data access object pattern

    Hello,
    I am trying to implement the Data Access Object pattern and I have the following bean:
    package com.netpepper.ecards;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import javax.faces.application.Action;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    * @author Julien Martin
    * Card class: represents the card sent from a member of the public (the sender)
    * to another member of the public (the recipient).
    public class Card {
         private static Log log = LogFactory.getLog(Card.class);
         private long id;
         private String from_email;
         private String to_email;
         private String image;
         private String bgcolor;
         private String font;
         private String from_name;
         private String to_name;
         private String message;
         private String title;
         private boolean received;
         private boolean sent;
         private String send_date;
         private String response;
          * Public empty no-arg constructor
         public Card() {}
          * Full-fledged constructor
         public Card(
              long id,
              String from_email,
              String to_email,
              String image,
              String bgcolor,
              String font,
              String from_name,
              String to_name,
              String message,
              String title,
              boolean received,
              boolean sent,
              String send_date) {
              setId(id);
              setFrom_email(from_email);
              setTo_email(to_email);
              setImage(image);
              setBgcolor(bgcolor);
              setFont(font);
              setFrom_name(from_name);
              setTo_name(to_name);
              setMessage(message);
              setTitle(title);
              setReceived(received);
              setSent(sent);
              setSend_date(send_date);
          * @return the background color choosed by the sender.
         public String getBgcolor() {
              return bgcolor;
          * @return the font choosed by the sender.
         public String getFont() {
              return font;
          * @return the sender's email.
         public String getFrom_email() {
              return from_email;
          * @return the sender's name.
         public String getFrom_name() {
              return from_name;
          * @return the card's id.
         public long getId() {
              return id;
          * @return the image choosed by the sender.
         public String getImage() {
              return image;
          * @return the message input by the sender.
         public String getMessage() {
              return message;
          * @return <code>true</code> if the card has been received, <code>false</code> otherwise.
         public boolean isReceived() {
              return received;
          * @return <code>true</code> if the card has been sent, <code>false</code> otherwise.
         public boolean isSent() {
              return sent;
          * @return the title choosed by the sender.
         public String getTitle() {
              return title;
          * @return the recipient's email.
         public String getTo_email() {
              return to_email;
          * @return the recipient's name.
         public String getTo_name() {
              return to_name;
          * @param the background color choosed by the sender.
         public void setBgcolor(String string) {
              bgcolor = string;
          * @param the font choosed by the sender.
         public void setFont(String string) {
              font = string;
          * @param the sender's email.
         public void setFrom_email(String string) {
              from_email = string;
          * @param the sender's name.
         public void setFrom_name(String string) {
              from_name = string;
          * @param the card's id.
         public void setId(long i) {
              id = i;
          * @param the image choosed by the sender.
         public void setImage(String string) {
              image = string;
          * @param the message input by the sender.
         public void setMessage(String string) {
              message = string;
          * @param <code>true</code> if the card has been received, <code>false</code> otherwise.
          * If the application attempts to set the received field to true,
          * then the received field of the Card object is persisted to database
          * and an email is sent to the sender to notify them that the card has been received.
         public void setReceived(boolean b) {
              if (this.received == false && b == true) {
                   Mailer m = new Mailer();
                   try {
                        m.sendAcknowlegement(
                             to_email,
                             from_email,
                             from_name,
                             to_name,
                             id);
                        Connection con = DBConnection.getConnection();
                        PreparedStatement ps =
                             con.prepareStatement(Queries.setReceivedQuery);
                        ps.setLong(1, this.id);
                        ps.executeUpdate();
                        con.close();
                        this.received = true;
                   } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
          * @param <code>true</code> if the card has been sent, <code>false</code> otherwise.
          * If the application attempts to set the send field to true,
          * then the sent field of the Card object is persisted to database.
         public void setSent(boolean b) {
              if (this.sent == false && b == true) {
                   try {
                        Connection con = DBConnection.getConnection();
                        PreparedStatement ps =
                             con.prepareStatement(Queries.setSentQuery);
                        ps.setLong(1, this.id);
                        ps.executeUpdate();
                        con.close();
                   } catch (SQLException e) {
                        log.error("ERROR: impossible to update the sent field");
                        e.printStackTrace();
          * @param the title choosed by the sender.
         public void setTitle(String string) {
              title = string;
          * @param the recipient's email.
         public void setTo_email(String string) {
              to_email = string;
          * @param the recipient's name.
         public void setTo_name(String string) {
              to_name = string;
          * @return the send date.
         public String getSend_date() {
              return send_date;
          * @param the send date.
         public void setSend_date(String string) {
              send_date = string;
          * @return <code>true</code> if email has been sent, <code>false</code> otherwise.
         public boolean sendEmail() {
              try {
                   Mailer sm = new Mailer();
                   sm.sendCard(
                        this.from_email,
                        this.to_email,
                        this.from_name,
                        this.to_name,
                        this.id);
                   return true;
              } catch (Exception e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   return false;
          * Retrieve the card from the database
         public static Card getCardFromId(int id) {
              Card c = new Card();
              c.id = id;
              try {
                   Connection con = DBConnection.getConnection();
                   PreparedStatement ps = con.prepareStatement(Queries.getCardFromID);
                   ps.setInt(1, id);
                   ResultSet rs = ps.executeQuery();
                   if (rs.next()) {
                        c.setBgcolor(rs.getString("db_bgcolor"));
                        c.setFont(rs.getString("db_font"));
                        c.setFrom_email(rs.getString("db_from_email"));
                        c.setTo_email(rs.getString("db_to_email"));
                        c.setFrom_name(rs.getString("db_from_name"));
                        c.setTo_name(rs.getString("db_to_name"));
                        c.setFont(rs.getString("db_font"));
                        c.setMessage((String) rs.getObject("db_message"));
                        c.setTitle(rs.getString("db_title"));
                        c.setSend_date(rs.getString("db_send_date"));
                        c.setImage(rs.getString("db_image"));
                        if (rs.getString("db_received").equals("y")) {
                             c.received = true;
                        } else if (rs.getString("db_received").equals("n")) {
                             c.setReceived(true);
                        if (rs.getString("db_sent").equals("y")) {
                             c.setSent(true);
                        } else if (rs.getString("db_sent").equals("n")) {
                             c.setSent(false);
                   System.out.println(c);
                   //con.close();
                   return c;
              } catch (SQLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   return null;
         public String toString() {
              return ("Title: " + this.title + ", " + "Id: " + this.id);
          * @param string
         public void setResponse(String string) {
              response = string;
         protected String saveCard() {
              try {
                   Connection con = DBConnection.getConnection();
                   PreparedStatement ps = con.prepareStatement(Queries.saveCard);
                   ps.setLong(1, (new java.util.Date()).getTime());
                   ps.setString(2, this.from_email);
                   ps.setString(3, this.to_email);
                   ps.setString(4, this.image);
                   ps.setString(5, this.bgcolor);
                   ps.setString(6, this.font);
                   ps.setString(7, this.from_name);
                   ps.setString(8, this.to_name);
                   ps.setString(9, this.message);
                   ps.setString(10, this.title);
                   ps.setString(11, this.send_date);
                   ps.executeUpdate();
                   con.close();
                   return "saved";
              } catch (SQLException e) {
                   log.error("ERROR: impossible to save the card");
                   e.printStackTrace();
                   return "notSaved";
         public Action getSaveCard() {
              return new Action() {
                   public String invoke() {
                        return saveCard();
    }The full source code for the project can be downloaded here:
    http://cours.java.free.fr/ecards-project/
    I would like to decouple the bean from the jdbc but I don't know how to. Can anyone help please?
    I found some sampes here http://access1.sun.com/codesamples/DataAccessObject.html
    but it does not have any update jdbc.
    Julien.

    Your DAO should have methods for getting and setting beans.
    For example:
    public Card getCard(long id){...}
    public void updateCard(Card c) {...}

  • Data access Objects

    Deepak,
    Can you throw some light on the 'Data access Objects" pattern? and how it can be used with Entity beans? I am trying to apply this to the following scenario and having a hard time.
    We need users to be transparent of the data retrieval from various sources like oracle database, flat files or legacy storage. If I use the data access object pattern it is easier to use java classes in place of entity beans.
    Thanks
    Shreyas Kamat

    Shreyas,
    [For those not familiar with our Data Access Object Pattern, the
    beta version of the pattern is available on JDC (needs JDC login) at:
    http://developer.java.sun.com/developer/restricted/patterns/DataAccessObject.html]
    Data Access Objects (or DAOs) are objects that hide the database
    implementation from data clients. Data clients are any objects
    that need to retrieve data from the data source. And the data source
    could be anything that contains data, not necessarily only RDBMSs.
    For example, an external system could be a data source.
    Now using DAOs with Entity beans is applicable only in bean-managed
    persistence (BMP) scenario. In BMP, the entity beans are responsible
    to provide the data load and store implementation in the ejbLoad()
    and ejbStore() methods of the bean implementation. Without using
    the DAOs, the entity bean class will contain all the JDBC code (assuming
    that the data source is an RDBMS), SQL, etc. This makes the
    entity bean class bloated and difficult to manage when changes
    are made to the data logic. In addition, this tightly couples the
    data source implementation with the entity bean implementation.
    By using DAOs, the ejbStore() and ejbLoad() methods are much
    simpler. Also, it is easier to change from one datasource implementation
    to another by replacing the DAOs. Further flexibility is possible
    by employing the DAO factory strategy as described in the DAO pattern
    in our catalog.
    Coming back to you point about making the data access transparent
    to the clients; it is possible to achieve this by using DAO and
    DAO factory strategy. In the current version of the pattern,
    included in the book, we provide sample code to show how
    to design DAO classes and to apply DAO factory strategy.
    On your last point about using java classes instead of entity beans, this
    is not the intention of the DAO pattern. Entity beans serve a different
    purpose in the architecture as coarse-grained transactional components.
    entity beans use DAOs in BMP implementations, but are not replaced
    by DAOs. However, DAO classes are reusable. The same DAO that is
    used by an entity bean to retrieve some data in one application scenario,
    can be reused by a servlet in another application scenario
    that needs the same data, but does not use entity beans.
    So bottom line is that DAOs address the need to data access and
    manipulation and work together with entity beans in BMP implementations.
    thanks,
    -deepak

  • Data Access Objects and associations....

    Ive got a few classes which are 'value based', and represent some configuration for some dynamic part of my application.
    I was going to employ the Data Access Objects pattern (http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html) to decouple the data source (either XML or RDB in this case) from the content.
    In my case though, I have associations between the content.
    E.g, an X contains 0..n Ys' which have 0..1 Zs'.
    So, X has 'getYs()' for example.
    Is the DAO pattern meant for cases like this, or just for single data object cases (E.g, 'Customer') with simple properties?
    I cant see any disadvantages for using it in my case, but wondered if any one has any thoughts on the design?

    The aim of the DAO is to hide the implementation of the datasource to the clients (i.e the classes using it). And the reason is the client should not care how the data is stored. It also means that I can change the way I store my data without changing the client(s) code (the client calls interface methods that do not change).
    If your code satisfies the above, it is implementing DAO, and it should not and does not matter how many Y's are in your X's or Z's...
    Always make a distinction between the general aim of a Design Pattern (its essence) and the (usually simple, even simplistic) examples supplied by different authors to illustrate the pattern.

  • Data Access Object  relationship with other tables

    Hi,
    I have two entities which are related. One is customer other is account.
    I need to get accounts of the customer as well , when I do a search for customer.
    I am using data access objects both for customer and account.
    Now where shall do the above mentioned search.
    Do I have to write one sql in Customer Data Access Object or does the Customer DAO has to refer to Account DAO to get account details.
    Which method is the best.
    Thanking You,
    Chamal.

    I have two entities which are related. One is
    customer other is account.
    I need to get accounts of the customer as well , when
    I do a search for customer.You might want to consider what you want to do if you need to display a list of customers.
    >
    I am using data access objects both for customer and
    account.
    Now where shall do the above mentioned search.
    Do I have to write one sql in Customer Data Access
    Object or does the Customer DAO has to refer to
    Account DAO to get account details.
    Which method is the best.
    If it was me the Account DAO would have a method that takes a customer id and returns a list of Accounts.
    Customer would have a method that used that method.
    That requires two queries though. Your requirements might drive the need for a single query (which returns two result sets.) If that was the case then I would still have the extraction logic in the Account class - the customer class would pass the extracted sub result set to it and it would return an account list.

  • Database access code in objects constructor, or in data access object

    Given an object that is stored in a database, is it better to have the database access code in a constructor method, or a data access layer object? E.g. I have a Person class
    public class Person{
    int Id;
    String name;
    int age;
    }When I want to read a person's details from the database, I could use a constructor something like this:
    public Person(int id){
    Connection con = getDatabaseConnection();
    ResultSet rs = con.createStatement().executeQuery("Select name, age from person where person_id = " + id);
    rs.next();
    this.name = rs.getString(1);
    this.age=rs.getInt(2);
    }Or I could use a method in a data access object :
    public Person getPerson(int id){
    Person p = new Person();
    Connection con = getDatabaseConnection();
    ResultSet rs = con.createStatement().executeQuery("Select name, age from person where person_id = " + id);
    rs.next();
    p.setName(rs.getString(1));
    p.setAge(rs.getInt(2));
    return p;
    }It seems to me that the constructor approach has two advantages
    (1) the SQL code is kept in the relevant class (so if I want to add a field to Person, I only have to make changes to the Person class)
    (2) I don't have to have a setter method for each field
    Is one or other of these ways generally recognized as 'best practise'?

    malcolmmc wrote:
    But then, on the other hand, everytime a Person gains a new field that's two places you have to change it. if the persistence interface is written in terms of the object and uses ORM, I don't have to touch the implementation. all i have to do is update the object, the database, and the mapping - just like you and your home brew ORM.
    besides, so what? i'd fear the resource leak, bad layering, more difficult testing more.
    Actually lately I've used annotations to label setters with database field names and run a simple home brew ORM to convert rows into objects even when not using a more complex persistence manager.home brew ORM? why is that necessary when you can choose from hibernate, ibatis, jdo, jpa, etc.? that's just nuts.
    %

  • Confusion... Data Access Object and Collection Class

    Please help me...
    i have a Book class in the library system, so normally i would have a Collection class eg. BookCollection class which keeps an array/ arrayList of Book objects. In BookCollection class i have methods like
    "searchBook(BookID)" which would return me a Book object in the array.
    But now i'm confused with Data Access Object... In sequence diagrams there's a "Data Access class" which is used to retrieve data from and send data to a database. So, if i have the Data Access class, do i still need BookCollection class? Because BookCollection serves as a database also rite? ...

    I think you're in the right rail.
    The BookCollection class could be still usefull if you will need to manage search results with more than onne record (e.g.: search by author name).

  • Data Access Objects (Wizard)

    Does SJSE 8 happen to have a wizard that allows you to use the database explorer and create Data Access Objects from tables? If not does anybody know of a good tool to do so. I will be working with IBM iSeries (DB2).

    I worked on a JDO runtime a long time ago during JDO's infancy, so I'm personally biased towards it . I like it because it allows you to treat your data objects as normal java objects instead of heavy-weight objects such as CMP beans. As I remember, the JDO runtime I worked on used byte code enhancer to inject code into your byte code to keep track of changes made by plain assignment statements. (Not sure if it works that way for other implementations.)
    You might want to check out the following link on SDN:
    http://java.sun.com/products/jdo/
    Also, there is FAQ on JDO vs. J2EE Persistence you should read before you make a decision:
    http://java.sun.com/j2ee/persistence/faq.html
    Good luck.

  • Managed Beans and Data Access Object

    I have a question / need help understanding how to configure backing bean and model objects so that memory and object creation/deletion is done as efficiently as possible.
    1. I have a .jsf page with a form and a commandbutton that submits the form inputs to a backing bean (enrollispbean is backing bean)
    <h:commandButton value="Enter" action="#{enrollispbean.insert}"/>
    2. The backing bean is used for form handling - the insert() method is used to read the data fields from the form and create a SQL string that will be submitted to a model object, DbInsert, that is used as a generic data access object that connects to the database and insert the SQL string:
    public class EnrollIspBean {
    private String beanvar1="";
    private String beanvar2= "";
    // DbInsert is data access object
    private DbInsert dbinsert = new DbInsert();
    public String insert (){
    String sqlstmt;
    sqlstmt = "INSERT INTO ispmain VALUES(beanvar1, beanvar2,..)"
    dbinsert.insert(sqlstmt);
    return "success"; }
    3. DbInsert is the data access object that contains a method, insert(), that accepts a sql string to insert into the database. This method contains the code to obtain a connection from the database connection pool and then execute the sql statement (note: error checking code not shown):
    public class DbInsert {
    public void insert(String sqlstmt) throws SQLException {
    Connection conn = null;
    GetDBConnection getdbconnection = new GetDBConnection();
    PreparedStatement stmt = null;
    conn = getdbconnection.getdbconn();
    stmt = conn.prepareStatement(sqlstmt);
    stmt.executeUpdate();
    stmt.close();
    conn.close();
    return;
    Where I need help understanding is how to set up the scope for the managed beans and data access object. Currently, I have the backing bean within the session scope (using the facesconfig.xml file). My main question is how to set up the scope for the Data Access Object - currently I do not have it as a managed bean within facesconfig.xml. Instead I am creating a new instance within the backing bean:
    private DbInsert dbinsert = new DbInsert();
    Is this the best way to do this? Will the DBInsert object now be tied to the session scope of the backing bean (i.e., when backing bean is deleted, the DbInsert object will be deleted from session scope as well.)
    Ideally I would like the data access object to be available as a shared object throughout the life of the application. When I was programming using a servlet approach, I would have created a servlet to load on startup. Now that I'm using java server faces, I'm confused about the scope / how to efficiently set up a data access object that I want to be available to all backing beans in the application.
    tnanks for any help understanding this.
    Tom

    I was thinking about setting the data access object as application scope so that it can be used by an backing bean to execute sql statements.
    If I do set it as application scope, however, if I do this, do I still need to declare a new instance of the object from within each bean that uses the object?
    For example do I need to declare a new instance of the data access object from within the bean? or, should I assume that there is always an instance of the bean available in the application scope, and if so, how do I reference it from within the bean?
    Bean Code:
    public class EnrollIspBean {
    // DbInsert is data access object
    private DbInsert dbinsert = new DbInsert();
    Finally, I understand performance may be an issue if I have one instance of the data access object available in the application scope - is there a way to make multiple instances available in the application scope?
    thanks

  • Data Access Object pattern (DAO)

    Sun's J2EE blueprints includes the DAO pattern:
    http://java.sun.com/blueprints/patterns/DAO.html
    I created some example DAO's:
    http://daoexamples.sourceforge.net
    http://daoexamples.sourceforge.net/xref/index.html
    Please send any feedback to sean /.at.\ seansullivan |.dot.| com

    Your example is beautiful, but what would be even more
    interesting to learn. How many lines of sql WOULD
    make StringBuffer the appropriate solution.It's not the number of lines, it's the number of Strings that will be appended at runtime. If all the Strings are literals, as in the OPs code, using StringBuffer will never be appropriate. It will always be slower than using +. That's a little misleading because + doesn't do anything at runtime when concatenating literals, the literals will be concatenated together at compile time. Usually SQL will contain a mixture of literals and non-literals. Generally, + will still be faster because it will be appending less Strings at runtime than StringBuffer, depending on the code.
    I suppose the question is how many Strings do you need to concatenate at runtime to make it worth while to use StringBuffer.
    Well, first of all, it's got to be more than two. The idea of using a StringBuffer is to avoid extra Object creation. If the + doesn't get compiled into StringBuffer appends, + between two Strings will create zero extras Objects; creating only the result String. The StringBuffer solution requires one extra Object; the StringBuffer. So in the case of concatenating only two Strings, the StringBuffer sotution is again inferior.
    When Concatenating three Strings you break even in the Object count. StringBuffer has an extra Object. 'Dumb' concatentation requires an extra Object.
    After three Strings. StringBuffer starts to come out ahead. But in reality, the difference is negligible. String concatenation is fast. I have to run tests 100s of thousands of times to get a clear difference in time. I find it unlikely that anyone will be concatenating enough Strings in a non-looping method to make it worth mucking up the code with StringBuffers. This is not a bottleneck.
    The time that it really counts is when you are concatenating inside loops. The compiler is not smart enough to optimize that type of code into an efficient StringBuffer solution. If you are concatenating to the same a String inside a loop, it is good practice to use a StringBuffer especially if the loop runs many times in a row or runs very often.
    The main point is for something like the OPs code, it doesn't really matter. Both versions will have essentially the same performance (very fast.) There is no reason to make the code less readable. I say, don't sacrifice readability just to make the code run more slowly. There are many ways to code less effecient without making it unreadable.

Maybe you are looking for

  • How can I print out my contacts from my ipad

    HHow can I print out my contacts from my iPad or iPhone?

  • How to limit the number of instances of an MDB?

    Hi, I am using jboss 4.0.5 AS, and we have an mdb which listens to the jboss's jms queue. We are using ejb 3. we are configuring MDB like this @MessageDriven(name="LongProcessMessageBean", activationConfig = { @ActivationConfigProperty(propertyName="

  • Third Party Font on Mac Mini

    I have a new mac mini with OS X, Version 10.4.5 and I am trying to load ITC Kabel font with font book and can't. My friend has a G5 with OS X, Version 10.4.6 (with Classic also loaded) and she can load the same font in her OS X font book. When I open

  • I cannot add a homemade video to itunes

    I made a video using Windows 8 Movie Maker. Now I want to add it to iTunes library and then burn. I have tried importing and dragging the video but it doesn't appear anywhere in iTunes. What am I doing wrong or is this impossible with Windows 8?

  • Macintosh clients, 802.1x and NAC.

    I'm prototyping a NAC setup which has to cater for Macintosh clients as well as Windows. I can get the Macs to authenticate via 802.1x (surprisingly easy using the built in software!) but what I can't do is setup a Posture Validation Rule to identify