Implementing 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

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..:-( You can only do this if you are using BMP. Else not possible. DAO are just objects which encapsulates the DB manipulation code.
If there is any releation ships between the beans (1-many,many-many etc)
you can take advantage of the relationships concept introduced in ejb 2.0.
HTH
Ashwani

Similar Messages

  • Implementing DAO Pattern in ABAP

    This discussion implement DAO pattern asked the question of how to develop a DAO pattern in ABAP but i'd like to go a little deeper.
    The only answer given suggested the following design pattern:
    I don't have an coded example here, but isn't it sufficient for this pattern  to build an interface with some get- and set-methods? This interface can be implemented by several classes with different data retrieval logic. Then a static factory-method could do the job to decide during runtime which actual class is instantiated, returning the interface.
    Can anyone give an abstract description of this implementation relative to an SAP module (How would one approach this implementation in MM, PM, FICO, HR)
    Can anyone see any issues in this design?
    Can anyone provide an alternate design?
    Are we missing any steps?
    Together we can build a solid abap DAO everyone can use.

    I started to read about DAO pattern some days ago and found this great blog post:
    ABAP Unit Tests without database dependency - DAO concept
    I am starting to implement unit test in my developments and DAO pattern seems to be a clever choice.
    Regards,
    Felipe

  • Implement DAO pattern

    In my application I have some database tables with a persistency class. Some other objects are implemented by calling the service bus, some others are implemented by function modules.
    I want that the developer doesn't need to know where the object is coming from.
    Therefore I want to implement the DAO pattern (Data Access Object).
    I'm new on abap objects, so can somebody give me a working example or blog, or guidelines how to code this pattern?

    I don't have an coded example here, but isn't it sufficient for this pattern  to build an interface with some get- and set-methods? This interface can be implemented by several classes with different data retrieval logic. Then a static factory-method could do the job to decide during runtime which actual class is instantiated, returning the interface.

  • 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

  • DAO depends on DAO but different implementation

    hi everybody!
    i have a problem in my application design ....
    I use DAO-Pattern to access objects which are persisted. my DAOs offers some common CRUD-operations. the bussiness-logic (session-handling, transaction-logic) is enculapsed in command-pattern. for the reason that the session-handling and transaction-logic depends on the underlying DAO implementation (transaction-handling hibernate is different to jdbc) there is a implementation dependency between DAOs and Command .... so we have the following structure ...
         DAO...
              User (create,read,update,delete)
              Groups(.....)
              Protocol(....)
         Command...
              UserAdd: start session / transaction ... user-create group-read protocol-create
    --- Implementations
         DAO:
              UserHibernate
              GroupsHibernate
              Protocol-Filebased
         Command:
              UserAddHibernateproblem is, that user and groups use a hibernate-implementation and protocol a file-based implementation ... so there are mixed DAO-Implementations in the AddUserCommand.
    how can i clean seperate the two implemenations from the other in the commands? because i don't wan't to have a hard-coded dependency to the file-based-protocol in the hibernate-user implementation.
    my solution would be to give the user-add command an attribute protocol-dao and call only the attribute in the UserAddHibernateCommand.
    but i am not very happy with this solution ... is there any better way?
    i hope you understand my problem(due to my bad english gg) and you can help me.

    Bill,
    This is a bug in the formEditor.vm template. The editor item is not set up to be a dependent item, you can fix this by adding the #ITEM_PARTIAL_TRIGGERS() macro to the <af:panelLabelAndMessage> element:
    <af:panelLabelAndMessage #ITEM_PROMPT_IN_FORM() #ITEM_RENDERED_IN_FORM()
    #ITEM_PARTIAL_TRIGGERS()
    Also, not that you might want to extend your expression to check for '', in addition to null, ADF Faces sometimes returns false when checkinf for an item being null,a and the checking for '' returns true.
    Steven Davelaar,
    JHeadstart Team.

  • Use DAO or plain SQL?

    I am building a two-tiered enterprise app with Swing client and RDBMS backend. Over the last two weeks I've tried applying the DAO pattern to my design, manullay creating numerous DTO and DAO classes. I'm now starting to wonder if it's really worth the effort.
    My system is not complicated enough to justify the use of automated OR mapping tools or CMP. Also, the development staff on my team, including myself, have had no expereience in OR mapping and EJB; all we've done in the past involve simple application that accesses the database directly using SQL. We also feel that using SQL directly is adequate in implementing all the functionalities of our system.
    Our initial motivation for implementing DAO was to maximize reuse of persistence code, make code more readable and insulate UI/logic code from change in database schema. But it seems we're now spending too much time thinking about how to map database entities to DTOs, what DAOs to have, what DAO methods to define, etc., whereas in the past to get something from the database we could just write an SQL statement.
    TIA.

    I wouldn't do any application without using DAOs and
    DTOs.
    Perhaps you are focusing to much on the examples
    rather than on the pattern itself. Just because the
    examples do it does not mean that you have to do it.
    You can do with with just one infrustructure class (to
    do the connections, statement, etc) and then the
    following....
    class MyDTO
    public String field1;
    public String field2;
    class MyDAO
    static void create(MyDTO p) {...}
    static void update(MyDTO p) {...}
    static void delete(MyDTO p) {...}
    static MyDTO getById(String id) {...}
    static ArrayList getBySomethingElse(String
    somethingElse) {...}
    }And of course if you don't need one of the above
    methods then do not implement it.i have been doing almost everything in dao but i m not so sure why dtos are so essential, if you write your pojo well, dtos seem to be totally not needed; unless of course you are passing them across networks in ejb systems, and even that, theses days xmls are recommended instead. am i right?
    and lately i havee started using hibernate which i think is great even for small not complecated projects: it does not complicate things, and further, you can still do things in dao with hibernate, i dont see any conficts there: hibernate, jdo are mostly mapping mechnism, and dao is a design pattern.

  • About DAO

    I have read something about DAO with the help of some sites. But I didnt clearly understand "In what scenario, we use them"?? If we dnt use this DAO concept, what happens?? Im not asking "HOW do we implement DAO", but my question is "WHY do we use DAO "..I got an answer for "how", but I didnt clearly understand for "why"..Please tell me with some clear explanations instead of single line answers.

    Well, there are really two high level patterns here. Assuming you are going from something like a service based architecture, you will either go service -> dao -> domain object. Or you will go service -> domain object -> dao. I think the first one is a bit easier to understand.
    If you opt for the first option, the service will create the dao (which should be stateless, e.g., no instance variables that are not static and final). You then call a method on the dao (say 'selectFoo()') passing in a primary key and having Foo returned. The other common use would be to create a new instance of Foo, in which case the service would call something like insertFoo() which would return your new object.
    The second option involves just a bit more indirection. On Foo, you would place methods such as update()/save(), delete(), etc. You still need a way to get an instance of Foo. So, you can either create an AbstractFactory or put static methods on Foo such as getInstance() and newInstance(). Foo will delegate its calls to a dao for the actual database operations.
    Now, in the first design, you have separated as much as possible the domain logic from the persistence logic. (You normally have to make a compromise such as putting the primary key of Foo in the domain object, since you need to let the dao know how to update or delete the record). The downside is that you now have to provide a number of getters and setters (or additional constructors) for Foo for the dao to use.
    In the second design, you have mingled the domain and persistence logic a lot more. However, since the methods are all defined on Foo, you can get away with far fewer getters/setters/constructors than in the first design. In fact, with the second design, you really do not need a DAO at all. You can leave the persistence methods completely within Foo.
    One advantage the first design has over the second design (at least superficially) is that you can have multiple dao's all creating a Foo from different sources (say, an Oracle database, a MySql database, a XML file, etc.) In my experience, most objects are persisted in a single way. You can still opt for the second design and have multiple persistence strategies. In this case, you would have a series of helper classes within Foo (nested, inner classes).
    The choice is up to you. Some people really want to move the persistence logic out of the model and make it a separate tier. That pushes you, a bit, torwards design 1. Some people really want to keep encapsulation, and this pushes you a bit towards design 2. There is no right or wrong answer, and you can mix both styles in your application.
    For the dao's themselves, you also have a number of options. You can keep them public objects in their own packages and create a separate persistence tier. Or you can keep the dao's in the same package, make them non-public where possible, and use them simply as helper objects for the dao. Finally, you can eliminate the dao altogether via anonymous/inner classes.
    In terms of how the dao is designed on a class level, it depends on whether you want to use vanilla jdbc, an orm such as hibernate or jpa, or a hybrid such as iBatis. Generally, all of them will either need the information needed to establish a connection. Generally, they will need to clean up resources such as statements, result sets and connections.
    You will likely want to use a connection pool, such as Jakarta Commons DBCP. This improves efficiency and moves the connection logic out of java and into configuration. If you opt for a container (whether J2EE or Spring or something similar), the whole picture gets a lot easier. These will generally clean up resources, perform transactional logic and obtain connections via either configuration or annotations. http://static.springsource.org/spring/docs/2.0.x/reference/jdbc.html.
    So, in a roundabout way of answering your question, there is no "harm" in not using dao's. Generally, a database will outlive the applicaation that created the data. So, separating persistence from domain logic has additional value there. You also gain the benefit of concentrating on SQL in one set of classes and remaining in the java world for your other objects. It also can help somewhat in reducing the size of your domain model classes.
    No right or wrong, it's just a convention to use them.
    - Saish

  • Simple JDBC framework

    Hi All,
    do you know any simple JDBC framework to use in implementing DAO layers ?
    I'm not looking for ORM framework (like hibernate) but something simpler just to avoid for instance opening connections, closing them, resultsets management in a lot of methods.
    Thanks
    ste

    I vote with Spring JDBC Template as well. Abstacts the plumbing all the control is yours.

  • Error : The value is not set for parameter number"

    Hello All,
    I am getting an error message when I tried modifying a program by adding a new ID column to a database table.
    All DML is working except the Delete. So to look at the delete method, I am setting the parameter correctly as can be seen in the code belwo.
    Can someone please take a quick look and let me know where I need to tweak the code further.
    Thanks
    Fm
    The piece of code is given below.
    /* File Modified */
    /* EmailSetupDao.java
    * Generated by the MDK DAO Code Generator
    package com.harris.mercury.setups.standard.emailsetup;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Vector;
    import org.apache.log4j.Logger;
    import com.harris.mercury.dao.CreateException;
    import com.harris.mercury.dao.DAO;
    import com.harris.mercury.dao.DataField;
    import com.harris.mercury.dao.Holder;
    import com.harris.mercury.dao.LocalResultProxy;
    import com.harris.mercury.dao.RemoveException;
    import com.harris.mercury.dao.ResultProxy;
    import com.harris.mercury.system.DatabaseHelper;
    import com.harris.mercury.system.database.dialect.Dialect;
    * The EmailSetupDao class
    public class EmailSetupDao implements DAO
    protected static Logger logger = Logger.getLogger(EmailSetupDao.class);
    /* This method is called by ResultProxies when they need
    * the data they have retrieved in a ResultSet mapped
    * to a holder.
    public Holder createHolder(ResultSet rs) throws SQLException
    EmailSetupHolder holder = new EmailSetupHolder(); // THE CODE GENERATOR NEEDS THIS VARIABLE
    try
    /* Assign the data into the new holder */
    // $$START_CREATEHOLDER_CONVERSIONS
    holder.setEmail_address( rs.getString("email_address") );
    holder.setLogin_id( rs.getString("login_id") );
    holder.setUser_name( rs.getString("user_name") );
    holder.setSmtp( rs.getString("smtp") );
    holder.setId(rs.getString("id") );
    // $$END_CREATEHOLDER_CONVERSIONS
    catch(SQLException sqle)
    logger.error(sqle, sqle);
    throw sqle;
    return holder;
    /* The findAll method returns a ResultProxy containing all the
    * records in the pucemailr table, unless an extended where clause
    * has been defined.
    public ResultProxy findAll(Connection con) throws SQLException
    LocalResultProxy result = null; // THE CODE GENERATOR NEEDS THIS VARIABLE
    // $$START_ALLFIND
    result = new LocalResultProxy(this,con, "select email_address, login_id, user_name, smtp, id from pucemailr"+makeOrderBy());
    // $$END_ALLFIND
    return result;
    /* Inserts a record into the pucemailr table using a EmailSetupHolder.
    * An exception is thrown if it is not sucessful.
    public void insert(Connection con, EmailSetupHolder holder) throws CreateException
    CreateException ce = null;
    PreparedStatement ps = null; // THE CODE GENERATOR NEEDS THIS VARIABLE
    try
    // Insert into the data base
    // $$START_INSERT_PS
         ps = con.prepareStatement("insert into pucemailr (email_address, login_id, user_name, smtp) values(?, ?, ?, ?) ");
    // $$END_INSERT_PS
    /* Assign the variables in the holder to their corresponding
    * indexes in the prepared statement
    ps = assignPreparedStatementValues(ps, holder, true) ;
    // Try the insert
    ps.executeUpdate();
    catch (SQLException se)
    ce = new CreateException(se.getMessage());
    catch (Exception ex)
    ce = new CreateException(ex.getMessage());
    } finally {
    DatabaseHelper.close(ps);
    // Throw exception if error occurred
    if (ce != null) {
    throw ce;
    /* This method will update a pucemailr record using the
    * supplied EmailSetupHolder. If an error occurs, an exception
    * is thrown.
    public void update(Connection con, EmailSetupHolder holder) throws Exception
    RuntimeException re = null;
    PreparedStatement ps = null; // THE CODE GENERATOR NEEDS THIS VARIABLE
    try
    // $$START_UPDATE_PS
         ps = con.prepareStatement("update pucemailr set email_address=?, login_id=?, user_name=?,smtp=? where id=?");
    // $$END_UPDATE_PS
    /* Assign the variables in the holder to their corresponding
    * indexes in the prepared statement
    ps = assignPreparedStatementValues(ps, holder, false) ;
    // Try the insert
    int ret = ps.executeUpdate();
    if (ret != 1)
    re = new RuntimeException("Update failed on table pucemailr in EmailSetupDao");
    catch (SQLException se)
    re = new CreateException(se.getMessage());
    catch (Exception ex)
    re = new RuntimeException(ex.getMessage());
    } finally {
    DatabaseHelper.close(ps);
    // Throw exception if error occurred
    if (re != null) {
    throw re;
    /* Using the EmailSetupHolder, this method locates records in the pucemailr table.
    * Null values found in the holder are not used in the search.
    * An exception is thrown if an error occurs.
    public ResultProxy find(Connection con, EmailSetupHolder holder) throws SQLException
    // THE CODE GENERATOR NEEDS THESE VARIABLES
    ResultProxy result = null;
    int needAnd = 0;
    StringBuffer selectStatement = new StringBuffer();
    // $$START_FIND
    selectStatement.append("select email_address, login_id, user_name, smtp, id from pucemailr ");
    if(holder.getId() != null)
    if ( needAnd > 0)
    selectStatement.append(" and ");
    else
    selectStatement.append(" where ");
    needAnd++;
    selectStatement.append("id like ");
    selectStatement.append("'"+ Dialect.getSafeDialect(con).escape(holder.getId())+"%'");
    if(holder.getEmail_address() != null)
    if ( needAnd > 0)
    selectStatement.append(" and ");
    else
    selectStatement.append(" where ");
    needAnd++;
    selectStatement.append("email_address like ");
    selectStatement.append("'"+ Dialect.getSafeDialect(con).escape(holder.getEmail_address())+"%'");
    if(holder.getLogin_id() != null)
    if ( needAnd > 0)
    selectStatement.append(" and ");
    else
    selectStatement.append(" where ");
    needAnd++;
    selectStatement.append("login_id like ");
    selectStatement.append("'"+ Dialect.getSafeDialect(con).escape(holder.getLogin_id())+"%'");
    if(holder.getUser_name() != null)
    if ( needAnd > 0)
    selectStatement.append(" and ");
    else
    selectStatement.append(" where ");
    needAnd++;
    selectStatement.append("user_name like ");
    selectStatement.append("'"+ Dialect.getSafeDialect(con).escape(holder.getUser_name())+"%'");
    if(holder.getSmtp() != null)
    if ( needAnd > 0)
    selectStatement.append(" and ");
    else
    selectStatement.append(" where ");
    needAnd++;
    selectStatement.append("smtp like ");
    selectStatement.append("'"+ Dialect.getSafeDialect(con).escape(holder.getSmtp())+"%'");
    // $$END_FIND
    result = new LocalResultProxy(this, con, selectStatement.toString()+makeOrderBy());
    return result;
    /* Creates an Order by clause */
    public String makeOrderBy()
    String result = "";
    // $$START_ORDERBY
    result = " order by smtp";
    // $$END_ORDERBY
    return result ;
    /* This method deltes a single record that matches all the
    * variables found in the EmailSetupHolder.
    * An exception is thrown if an error occurs.
    public void delete(Connection con, EmailSetupHolder holder) throws RemoveException
    RemoveException re = null;
    PreparedStatement ps = null; // THE CODE GENERATOR NEEDS THIS VARIABLE
    boolean hasVars = false;
    StringBuffer deleteSQL = new StringBuffer();
    deleteSQL.append( "delete from pucemailr where " );
    // $$START_DELETE_SQL
    if (hasVars)
    deleteSQL.append(" and ");
    if (holder.getEmail_address() != null) {
    deleteSQL.append("email_address=?") ;
    } else {
    deleteSQL.append("email_address is null");
    hasVars = true;
    if (hasVars)
    deleteSQL.append(" and ");
    if (holder.getLogin_id() != null) {
    deleteSQL.append("login_id=?") ;
    } else {
    deleteSQL.append("login_id is null");
    hasVars = true;
    if (hasVars)
    deleteSQL.append(" and ");
    if (holder.getUser_name() != null) {
    deleteSQL.append("user_name=?") ;
    } else {
    deleteSQL.append("user_name is null");
    hasVars = true;
    if (hasVars)
    deleteSQL.append(" and ");
    if (holder.getSmtp() != null) {
    deleteSQL.append("smtp=?") ;
    } else {
    deleteSQL.append("smtp is null");
    hasVars = true;
    if (hasVars)
    deleteSQL.append(" and ");
    if (holder.getSmtp() != null) {
    deleteSQL.append("id=?") ;
    } else {
    deleteSQL.append("id is null");
    hasVars = true;
    // $$END_DELETE_SQL
    try
         ps = con.prepareStatement(deleteSQL.toString());
    /* Assign the variables in the holder to their corresponding
    * indexes in the prepared statement
    int index = 1 ;
    // $$START_DELETE_VARS
    /* if( holder.getEmail_address() != null) {
    ps.setString(index, holder.getEmail_address() );
    index ++;
    if( holder.getLogin_id() != null) {
    ps.setString(index, holder.getLogin_id() );
    index ++;
    if( holder.getUser_name() != null) {
    ps.setString(index, holder.getUser_name() );
    index ++;
    if( holder.getSmtp() != null) {
    ps.setString(index, holder.getSmtp() );
    index ++;
    if( holder.getId() != null) {
    ps.setString(index, holder.getId() );
    index ++;
    // $$END_DELETE_VARS
    // Try the insert
    int ret = ps.executeUpdate();
    if (ret != 1)
    re = new RemoveException("Delete failed on table pucemailr in EmailSetupDao");
    catch (SQLException se)
    re = new RemoveException(se.getMessage());
    catch (Exception ex) {
    re = new RemoveException(ex.getMessage());
    } finally {
    DatabaseHelper.close(ps);
    // Throw exception if error occurred
    if (re != null)
    throw re;
    /* This method finds records in pucemailr table that match the
    * supplied where clause.
    * An exception is thrown if an error occurs.
    public ResultProxy advancedFind(Connection con, String whereclause) throws SQLException
    // THE CODE GENERATOR NEEDS THIS VARIABLE AND THE PARAMETER VARIABLE 'whereclause'
    StringBuffer selectStatement = new StringBuffer();
    // $$START_ADVANCEDFIND
    selectStatement.append("select email_address, login_id, user_name, smtp, id from pucemailr ");
    // $$END_ADVANCEDFIND
    selectStatement.append(" where ");
    selectStatement.append(whereclause);
    return new LocalResultProxy(this,con, selectStatement.toString()+makeOrderBy());
    /* This methods returns a Vector of DataField objects that
    * map the columns in the pucemailr table for the
    * advanced find Where Clause Generator in the client. The extended
    * where clause will be applied if one exists for this DAO.
    public Vector<DataField> getQueryFields() {
    Vector<DataField> v = new Vector<DataField>() ; // THE CODE GENERATOR NEEDS THIS VARIABLE
    // $$START_QUERYFIELDS
    v.addElement( new DataField( "email_address", "Email address", DataField.STRING ) ) ;
    v.addElement( new DataField( "login_id", "Login id", DataField.STRING ) ) ;
    v.addElement( new DataField( "user_name", "User name", DataField.STRING ) ) ;
    v.addElement( new DataField( "smtp", "Smtp", DataField.STRING ) ) ;
    v.addElement( new DataField( "id", "Id", DataField.STRING ) ) ;
    // $$END_QUERYFIELDS
    return v;
         * Jira Issue NS 30679 - Faiz Qureshi March 7, 2013
         * @param ps
         * @param holder
         * @param isInsert - Added Boolean parameter so the id parameter does not get passed for Insert DML statements
         * @return
         * @throws Exception
    public PreparedStatement assignPreparedStatementValues(PreparedStatement ps, EmailSetupHolder holder, boolean isInsert)
    throws Exception
    // $$START_PS_SETS
    if( holder.getEmail_address() != null)
    ps.setString(1, holder.getEmail_address() );
    else
    ps.setNull(1, java.sql.Types.VARCHAR);
    if( holder.getLogin_id() != null)
    ps.setString(2, holder.getLogin_id() );
    else
    ps.setNull(2, java.sql.Types.VARCHAR);
    if( holder.getUser_name() != null)
    ps.setString(3, holder.getUser_name() );
    else
    ps.setNull(3, java.sql.Types.VARCHAR);
    if( holder.getSmtp() != null)
    ps.setString(4, holder.getSmtp() );
    else
    ps.setNull(4, java.sql.Types.VARCHAR);
    if (!isInsert){
         if( holder.getId() != null)
         ps.setString(5, holder.getId() );
         else
         ps.setNull(5, java.sql.Types.VARCHAR);
    // $$END_PS_SETS
    return ps;
    /* Do not delete this tag, it is reserved for adding new methods to the DAO */
    // $$ START_MDK_RESERVED
    // $$START_EDITABLE_SUB_TABLE_NAME
    * Returns the table names used in this DAO
    * @return the table names used in this DAO
    public String[] getTableNames() {
    // $$START_UNEDITABLE_SUB_TABLE_NAME
    String[] tableNames = new String[] {"pucemailr"};
    // $$END_UNEDITABLE_SUB_TABLE_NAME
    return tableNames;
    // $$END_EDITABLE_SUB_TABLE_NAME
    // $$START_EDITABLE_SUB_FIND
    * Using the EmailSetupHolder, this method locates records in the pucemailr table.
    * Null values found in the holder are not used in the search.
    * An exception is thrown if an error occurs.
    * @param con The database connection
    * @param holder holder containing the values to generate a query upon
    * @param orderBy The order by clause. Note, you must specify the "ORDER BY". If you forget to add a
    * space in front of the order by, it will be automatically handled. Specify null to use the default
    * or empty string for no ordering.
    * @return The result of the search
    * @throws SQLException if an error occurs in the search.
    public ResultProxy find(Connection con, EmailSetupHolder holder, String orderBy) throws SQLException
    // THE CODE GENERATOR NEEDS THESE VARIABLES
    ResultProxy result = null;
    int needAnd = 0;
    StringBuffer selectStatement = new StringBuffer();
    // $$START_FIND
    selectStatement.append("select email_address, login_id, user_name, smtp, id from pucemailr ");
    if(holder.getEmail_address() != null)
    if ( needAnd > 0)
    selectStatement.append(" and ");
    else
    selectStatement.append(" where ");
    needAnd++;
    selectStatement.append("email_address like ");
    selectStatement.append("'"+ Dialect.getSafeDialect(con).escape(holder.getEmail_address())+"%'");
    if(holder.getLogin_id() != null)
    if ( needAnd > 0)
    selectStatement.append(" and ");
    else
    selectStatement.append(" where ");
    needAnd++;
    selectStatement.append("login_id like ");
    selectStatement.append("'"+ Dialect.getSafeDialect(con).escape(holder.getLogin_id())+"%'");
    if(holder.getUser_name() != null)
    if ( needAnd > 0)
    selectStatement.append(" and ");
    else
    selectStatement.append(" where ");
    needAnd++;
    selectStatement.append("user_name like ");
    selectStatement.append("'"+ Dialect.getSafeDialect(con).escape(holder.getUser_name())+"%'");
    if(holder.getSmtp() != null)
    if ( needAnd > 0)
    selectStatement.append(" and ");
    else
    selectStatement.append(" where ");
    needAnd++;
    selectStatement.append("smtp like ");
    selectStatement.append("'"+ Dialect.getSafeDialect(con).escape(holder.getSmtp())+"%'");
    if(holder.getId() != null)
    if ( needAnd > 0)
    selectStatement.append(" and ");
    else
    selectStatement.append(" where ");
    needAnd++;
    selectStatement.append("Id like ");
    selectStatement.append("'"+ Dialect.getSafeDialect(con).escape(holder.getId())+"%'"); }
    // $$END_FIND
    result = new LocalResultProxy(this, con, selectStatement.toString() + (orderBy == null ? makeOrderBy() : com.harris.mercury.system.utils.StringUtils.padLeft(orderBy)));
    return result;
    // $$END_EDITABLE_SUB_FIND
    // $$START_EDITABLE_SUB_FINDALL
    * The findAll method returns a ResultProxy containing all the records in the pucemailr table,
    * unless an extended where clause has been defined.
    * @param con The database connection
    * @param orderBy The order by clause. Note, you must specify the "ORDER BY". If you forget to add a
    * space in front of the order by, it will be automatically handled. Specify null to use the default
    * or empty string for no ordering.
    * @return The result of the search
    * @throws SQLException if an error occurs in the search.
    public ResultProxy findAll(Connection con, String orderBy) throws SQLException
    LocalResultProxy result = null; // THE CODE GENERATOR NEEDS THIS VARIABLE
    // $$START_UNEDITABLE_SUB_FINDALL
    result = new LocalResultProxy(this,con, "select email_address, login_id, user_name, smtp, id from pucemailr" + (orderBy == null ? makeOrderBy() : com.harris.mercury.system.utils.StringUtils.padLeft(orderBy)));
    // $$END_UNEDITABLE_SUB_FINDALL
    return result;
    // $$END_EDITABLE_SUB_FINDALL
    // $$START_EDITABLE_SUB_ADVANCEDFIND
    * This method finds records in pucemailr table that match the supplied where clause.
    * @param con The database connection
    * @param whereclause The where clause for the select statement - do not include the "where" - it
    * will be automatically prepended
    * @param orderBy The order by clause. Note, you must specify the "ORDER BY". If you forget to add a
    * space in front of the order by, it will be automatically handled. Specify null to use the default
    * or empty string for no ordering.
    * @return The result of the search
    * @throws SQLException if an error occurs in the search.
    public ResultProxy advancedFind(Connection con, String whereclause, String orderBy) throws SQLException
    // THE CODE GENERATOR NEEDS THIS VARIABLE AND THE PARAMETER VARIABLE 'whereclause'
    StringBuffer selectStatement = new StringBuffer();
    // $$START_ADVANCEDFIND
    selectStatement.append("select email_address, login_id, user_name, smtp, id from pucemailr ");
    // $$END_ADVANCEDFIND
    selectStatement.append(" where ");
    selectStatement.append(whereclause);
    selectStatement.append((orderBy == null ? makeOrderBy() : com.harris.mercury.system.utils.StringUtils.padLeft(orderBy)));
    return new LocalResultProxy(this,con, selectStatement.toString());
    // $$END_EDITABLE_SUB_ADVANCEDFIND
    // $$ END_MDK_RESERVED
    }

    First thing to do is to edit the post and use some tags to format the code as it is unreadable and too much!
    Read the FAQ (https://forums.oracle.com/forums/help.jspa) to find out how to do this.
    Next we need to know the jdev version you are using!
    As the code is generated I would first try to generate it again after the db change.
    Timo

  • Are you all for DB code in GUI?

    I am working on a project where the company who makes the object oriented database we use told us to put the DB calls in the Swing GUI objects for performance reasons.
    The senior engineers on the project at the time (I came later) didn't put up a red flag that: 1. that significantly ties us to their DB (how convenient) and 2. maybe that just means we need to use a different DB if we should buck industry standards to use it effectivily.
    I was the first to buck their idea and I implemented DAO pattern. I literally had to argue with those who have been working here before me because I did this.
    So I ask, is it me or are my points 1 & 2 above valid no matter what the DB company says? Are there valid situations you can see for putting the DB code in the GUI on a project with 10 developers (just to give a relative size of the project)? I just need a reality check since the people I work with don't agree.
    Oh, yeah, and by the way, we have a Swing application that hits the central DB AND a web app that does as well. Of course there is some functionality that is to be displayed in both apps but not all functionality is repeated. Maybe that will help with your decision as well.
    thanks.

    These guys have their heads way up their asses. You are right. This is not going to cause performance issues. In fact if you aren't really careful, putting this is the GUI code is going to screw up the performance of the GUI.
    I don't know where your coworkers are getting these ideas from but they are patently absurd. Good for you for sticking to your guns. I know this can be extremely frustrating.
    If you are really taking heat on this, you should but the burden of proof on the people who are making these claims. Ask them how this will improve performance.

  • Using one object in multiple threads

    Are there any drawbacks in using one instance of an object in several threads simultaneously, if this object has no instance variables?
    I need to implement DAO in my project and I just wonder why DAOFactory every time creates a new DAO object, when DAO object doesn't have any instance variables?

    Are there any drawbacks in using one instance of an
    object in several threads simultaneously, if this
    object has no instance variables?
    I need to implement DAO in my project and I just
    wonder why DAOFactory every time creates a new DAO
    object, when DAO object doesn't have any instance
    variables?I don't think there are any problems with this. Since you have no instance variables there isn't really any overlap between the two threads.

  • How to create a tableview for this ??

    Hey, i have been stuck to this part for a long time and not able to find any answers, may be i can get some help from you guys.
    See i have a scenario where i have different "items",out of which each will belong to a predefined category. These items have names and then different types(depend on the category), each of these types in turn have a price.
    For example if I have Item1(Bottle Of Water),belongs to category1 and it has different types : 200ml ,500 ml, 1000ml with price tags of 10,20,30 respectively.
    Similarly,I have Item2(Box of Butter),belongs to category2 and it has different types : 100 gm, 200 gm with price tags of 15 and 25 respectively.
    Now, i want these data to be shown on a editable table,when i press on a category button,all items belonging to the category(having the same types) must be displayed, with the headings divided into :
    On pressing category 1
    NAME | PRICE |
    | 200ml |500ml|1000ml |
    | |
    Bottle Of Water | 10 | 20 | 30 |
    On pressing category 2
    NAME | PRICE |
    | 100gm | 200ml |
    | |
    Box Of Butter | 15 | 25 |
    So i want a dyanamic table which can have dynamic nested columns.
    I was trying to make a table from the class
    public class ItemVO()
    String itemName;
    List<ItemTypeVO> type;
    and My ItemTypeVO has the following attributes :
    public class ItemTypeVO()
    String typeName;
    Integer price;
    But m not able to get anywhere with it.
    Many a places i have found dynamic columns with attributes like this :
    public class ItemVO()
    String itemName;
    ItemTypeVO type;
    But this doesnt suit my functionality. i guess .
    Can anybody help me with what change can i make in my class, so that i can make a table and supply me with some code as well.
    Thanks in advance.

    I don't really know what you are trying to do in this Test class.
    I mocked this up with the object model I suggested and a mock data access object which just hard codes a few items, and it works just fine.
    Type.java
    package itemtable;
    public class Type {
      private final String name ;
      public Type(String name) {
        this.name = name ;
      public String getName() {
        return name ;
    }Category.java
    package itemtable;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    public class Category {
      private final List<Type> types ;
      private final String name ;
      public Category(String name, List<Type> types) {
        this.name = name ;
        this.types = new ArrayList<Type>();
        this.types.addAll(types);
      public List<Type> getTypes() {
        return Collections.unmodifiableList(types);
      public String getName() {
        return name ;
      @Override
      public String toString() {
        return name ;
    }Item.java
    package itemtable;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import javafx.beans.property.DoubleProperty;
    import javafx.beans.property.ReadOnlyObjectProperty;
    import javafx.beans.property.SimpleDoubleProperty;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.property.StringProperty;
    public class Item {
      private final StringProperty name ;
      private final ReadOnlyObjectProperty<Category> category ;
      private final Map<Type, DoubleProperty> prices ;
      public Item(String name, Category category, Map<Type, Double> prices) {
        this.name = new SimpleStringProperty(name);
        this.category = new SimpleObjectProperty<Category>(category);
        this.prices = new HashMap<Type, DoubleProperty>();
        for (Type type : prices.keySet()) {
          validateType(type);
          this.prices.put(type, new SimpleDoubleProperty(prices.get(type)));
      public String getName() {
        return name.get();
      public Category getCategory() {
        return category.get();
      public double getPrice(Type type) {
        validateType(type);
        return prices.get(type).get();
      public void setName(String name) {
        this.name.set(name);
      public void setPrice(Type type, double price) {
        validateType(type);
        prices.get(type).set(price);
      public StringProperty nameProperty() {
        return name ;
      public ReadOnlyObjectProperty<Category> categoryProperty() {
        return category ;
      public DoubleProperty priceProperty(Type type) {
        return prices.get(type);
      private void validateType(Type type) {
        final List<Type> allowedTypes = category.get().getTypes();
        if (! allowedTypes.contains(type)) {
          throw new IllegalArgumentException("Cannot set a price for "+type.getName()+": it is not a type for the category "+category.getName());
    }DAO.java
    package itemtable;
    import java.util.List;
    public interface DAO {
      public List<Category> getCategories();
      public List<Item> getItemsByCategory(Category category);
    }MockDAO.java
    package itemtable;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    public class MockDAO implements DAO {
      private final List<Category> categories ;
      private final Map<Category, List<Item>> itemLookup ;
      public MockDAO() {
        final Type spreadType100g = new Type("100g");
        final Type spreadType200g = new Type("200g");
        final Type drinkType200ml = new Type("200ml");
        final Type drinkType500ml = new Type("500ml");
        final Type drinkType1000ml = new Type("1000ml");
        final Category spreads = new Category(
            "Spreads",
            Arrays.asList(spreadType100g, spreadType200g)
        final Category drinks = new Category(
            "Drinks",
            Arrays.asList(drinkType200ml, drinkType500ml, drinkType1000ml)
        final Map<Type, Double> waterPrices = new HashMap<Type, Double>();
        waterPrices.put(drinkType200ml, 10.0);
        waterPrices.put(drinkType500ml, 20.0);
        waterPrices.put(drinkType1000ml, 30.0);
        final Map<Type, Double> pepsiPrices = new HashMap<Type, Double>();
        pepsiPrices.put(drinkType200ml, 25.0);
        pepsiPrices.put(drinkType500ml, 45.0);
        pepsiPrices.put(drinkType1000ml, 75.0);
        final Map<Type, Double> butterPrices = new HashMap<Type, Double>();
        butterPrices.put(spreadType100g, 15.0);
        butterPrices.put(spreadType200g, 25.0);
        final Map<Type, Double> margarinePrices = new HashMap<Type, Double>();
        margarinePrices.put(spreadType100g, 12.0);
        margarinePrices.put(spreadType200g, 20.0);
        final Map<Type, Double> mayoPrices = new HashMap<Type, Double>();
        mayoPrices.put(spreadType100g, 20.0);
        mayoPrices.put(spreadType200g, 35.0);
        final Item water = new Item("Water", drinks, waterPrices);
        final Item pepsi = new Item("Pepsi", drinks, pepsiPrices);
        final Item butter = new Item("Butter", spreads, butterPrices);
        final Item margarine = new Item("Margarine", spreads, margarinePrices);
        final Item mayonnaise = new Item("Mayonnaise", spreads, mayoPrices);
        this.categories = Arrays.asList(drinks, spreads);
        this.itemLookup = new HashMap<Category, List<Item>>();
        itemLookup.put(drinks, Arrays.asList(water, pepsi));
        itemLookup.put(spreads, Arrays.asList(butter, margarine, mayonnaise));
      @Override
      public List<Category> getCategories() {
        return categories ;
      @Override
      public List<Item> getItemsByCategory(Category category) {
        return itemLookup.get(category);
    }ItemTable.java
    package itemtable;
    import javafx.application.Application;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.scene.Scene;
    import javafx.scene.control.ChoiceBox;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableColumn.CellDataFeatures;
    import javafx.scene.control.TableView;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.scene.layout.BorderPane;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    public class ItemTable extends Application {
      @Override
      public void start(Stage primaryStage) {
        final DAO dao = new MockDAO();
        final ChoiceBox<Category> choiceBox = new ChoiceBox<Category>();
        choiceBox.getItems().setAll(dao.getCategories());
        final TableView<Item> table = new TableView<Item>();
        final TableColumn<Item, String> nameCol = new TableColumn<Item, String>("Name");
        nameCol.setCellValueFactory(new PropertyValueFactory<Item, String>("name"));
        final TableColumn<Item, Double> priceCol = new TableColumn<Item, Double>("Price");
        table.getColumns().addAll(nameCol, priceCol);
        choiceBox.getSelectionModel().selectedItemProperty()
            .addListener(new ChangeListener<Category>() {
              @Override
              public void changed(ObservableValue<? extends Category> observable, Category oldValue, Category newValue) {
                table.getItems().clear();
                priceCol.getColumns().clear();
                for (final Type type : newValue.getTypes()) {
                  final TableColumn<Item, Number> col = new TableColumn<Item, Number>(type.getName());
                  col.setCellValueFactory(new Callback<CellDataFeatures<Item, Number>, ObservableValue<Number>>() {
                    @Override
                    public ObservableValue<Number> call(CellDataFeatures<Item, Number> cellData) {
                      Item item = cellData.getValue();
                      if (item == null) {
                        return null;
                      } else {
                        return item.priceProperty(type);
                  priceCol.getColumns().add(col);
                table.getItems().setAll(dao.getItemsByCategory(newValue));
        BorderPane root = new BorderPane();
        root.setTop(choiceBox);
        root.setCenter(table);
        Scene scene = new Scene(root, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
      public static void main(String[] args) {
        launch(args);
    }

  • Covariant Method Arguments/Returntypes on abstract methods

    Hi all,
    can someone enlight me - please!
    is there a special reason, why i cannot use the new jdk 5 covariant arguments/returntype feature in conjunction with abstract methods???
    I cannot find a reason anywhere!
    I did something like this:
    public interface DAO {
      public boolean save(Base b);
      public Base read(Long id);
    public abstract class AbstractBaseDAO implements DAO {
      public abstract boolean save(Base b);
      public abstract Base read(Long id);
    public class PersonDAO extends AbstractBaseDAO {
      public boolean save(Person p) {
      public Person read(Long id) {
    Of course Person extends Base ...
    Any hints, etc. are welcome!
    kind regards
    K:)

    And if it does apply to args, won't it have to go the other way?
    That is, if the interface/parent class takes Person as an arg, then the subclass can take Base.
    The way you have it, the interface requires you to accept Base as an arg--ANY Base, but your subclass' save method requires a Person, so it won't work with a non-person base. The subclass isn't honoring its parent's contract. Covariance won't change that.

  • Does the DOA need to be an session bean as well?

    Hi there,
    I been working in this problem for days, I am a bit confuse, I have created a session bean which contains biz logic and EAO layer,
    I understand that we can get the persistence in EJB with @PersistenceContext private EntityManager em;
    Correct me if I am wrong I am a bit sceptical to use the em in the session bean. (there been lot of arguments stated that we need to ditch the DAO)
    BUT, still I would want use EntityManager in the EAO layer because of the mobility of the DAO layer in the future.
    So I have implemented DAO design pattern at below but is not working, is giving me:
    Unable to get an Entity Manager Instance
    javax.naming.NameNotFoundException: No object bound to name java:comp/env/persistence/em
    I am so confuse, does the DAO need to be a session bean as well?
    Edited by: lizaliz on Aug 13, 2009 8:15 AM

    Using the EM in a session bean is one of the preferred ways of manageing persistence. Take a look at *'Pro EJB 3'* by Mike Keith and Merrick Schincariol. Extracts are avialable on google books - they give a good overview of using this approach.
    It is a bit weird initially as with EJB 2 you had your session beans (business tier) and your entity beans for the data tier so using a session bean seemed to conflict with what was recognised. And besides if you want to inject a Persistence Context or Factory you need to do it in a managed class - like an EJB!
    m

  • 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.

Maybe you are looking for

  • I can't download apps in creative cloud

    I am on Mavericks, and I can't seem to download apps. I looked for the error log in Library/logs/Adobe, and I don't see a log in there.

  • Unmountabl​e_boot_vol​ume

    First and foremost, my laptop is a Satellite E105-S1402 which came with windows vista, and I upgraded to windows 7 last year without any problems until now. Every time I attempt to boot up windows 7 the screen freezes, goes black, and then my cursor

  • KEEP LOSING MY BOOKMARKS

    Keep losing my bookmarks when signing on and off, and mostly when i reset Firefox to stop freezeups which happen quite often

  • Lumia 800 Sound problems on call

    Hello guys. I wanted to know if anyone has ever happened to this thing with this beautiful terminal. Many times when I answer a call can not hear who's calling me and after many tests I noticed that, if when I answer I hear a noise as if it were turn

  • Adobe Premiere Elements 9 Exporting in 1080i/p

    I am trying to make an introduction for my friend, and I am only using the text tool in Adobe Premiere, this should be high definition as it is. Although whenever I got to export something in 1080i or 1080p, what comes out on my desktop is the video