DAO pattern question

According to the DAO pattern, all fields of the table has to be put in the class, e.g. if I have a table called customer, I have to create a Customer class and then I have another class called CustomerDAO class. In CustomerDAO, I should have a method called getCustomer that returns Customer. But if my table is quite large, and I don't need to get all the attributes of the customer every time, what approach should I use, do I define another method to return, e.g. customer name. customer age etc.? Is there any standard convention?
Thanks

hi,
according to my understanding, u should use Value Object pattern.
for Example:
In Customer table if u have Id, name.
then u have CustomerVO in which u have the following code.
public class CustomerVO
private Long id;
private String name;
public Long getID()
return this.id;
public String getName()
return this.name;
public void setID(Long id)
return this.id=id;
public String setName(String name)
return this.name=name;
So now u have craete object of CustomerVO and get ur required fields only and Enjoy!!!!!!!!!

Similar Messages

  • 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

  • Question about DAO pattern

    Greetings.
    If I'm using EJB's in my application when does DAO fits in?? I mean, it is DAO an alternative to EJB's or a complement ??
    Thanks in advance.

    DAO fits in if you are using entity beans using bean managed persistence. In this case, the DAO brokers the database calls during the EJB's lifecycle. The other instance when you would use DAO would be if you forgo entity beans altogether. In this model, stateful or stateless session beans would use DAO's to broker the database calls directly, outside of the normal entity bean lifecycle. The DAO pattern can also be used with POJO's (plain 'ole Java objects).
    The only instance where DAO would not apply is in the case of a container managed entity bean. In this case, there is no need to write a DAO, as the container will persist the bean for you.
    - Saish
    "My karma ran over your dogma." - Anon

  • 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

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

  • 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)?

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

  • 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

  • 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)?

  • 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

  • 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

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

  • DAO pattern Value Objects and Data Streams

    Suppose we have a PersonVO (java bean) with simple attributes i.e. first and last name then the DAO is quite simple and clients of the DAO layer pass VO back and forth (really cleanly).
    But it is a different story if a person has a picture. If the picture is small then we
    could define a field that is simple an array of bytes i.e. byte pic[], and would work ,
    but will not scale if our pic becomes too large or there are lots of persons.
    How can streams be used in this case ? (without dao code leaking into the client layer) and does this break the DAO pattern ?

    I can picture not saving the image bytes themselves
    but a link to a JPG or GIF on the file system.And how would that be guarenteed on a cluster? Or even per OS?
    Putting streams into a database like that can choke
    performance. Can't do WHERE clauses on byte
    streams.For example in PostgreSQL:
    CREATE TABLE images (
      name VARCHAR(32) NOT NULL,
      image bytea NOT NULL,
      imagetype VARCHAR(4),
      CONSTRAINT image_pk PRIMARY KEY (name)
    );After retrieving the image into a byte[] you can either
    - directly serve it to the client (browser) over HTTP through a servlet
    (don't forget to set your content type through HttpServletResponse.setContentType())
    - convert the byte[] to a java.awt.image.BufferedImage using javax.imageio.ImageIO.read(byte[]), and ofcourse do everything you want (including transformations) from there.
    - What ever you can think off.
    Now if you're passing that VO to a JSP, the link to
    the image on the server file system fits nicely into
    the <img> tag and Bob's your uncle.But this will still not be guarenteed to work on a cluster, across platforms, etc.
    10 % 0
    java.lang.ArithmeticException: / by zero;-)

  • DAO Pattern Confusion

    Hello,
    Have started developing with J2EE recently, moving up from J2SE. With regards to persistance of data to a database I have been looking at the DAO pattern. I am a little confused about this pattern, so I hope someone may be able to clear a few things up.
    As I understand it the Transfer Object (TO) can be a simple java bean with getter and setter methods.
    The DAO can only have four methods, create, read, update and delete. I am a little confused here, because as I see it, we can only have these four methods to read/write from/to the TO.
    Isn't this very limiting? For example, the update statement of the DAO will have to have a TO which has already been populated, for this to occur an already populated TO has to be generated (a read on the DAO) and then the required values changed via the get/set methods of the TO. Then a method of the DAO has to be called to persist this data to the database.
    This would cause difficulties if we wanted to implement optimistic locking for example, where we wanted to check if a row had been changed before commiting the change (to prevent lost updates).
    Would it not be better to have many methods in the DAO, and a customer TO for each one? E.g. methods such as:
    TO to = new TO();
    to.setState("new");
    to.setWhere("old");
    dao.updateState(TO to)
    Such a design would let us update the state of a row in the database to "new" where the state previously was "old" and hence be a basic implementation of optimistic locking.
    Or are we completely missing the point!
    Many thanks,

    >>
    IMO, this model is broken. TO's, as traditionally
    implemented, are read-write. In most cases, it is
    easier to code a TO as read-only. Provideinstance
    values in the constructor and then expose onlygetter
    methods. One possible implementation is to havethe
    DAO and the TO (or preferably model object) in the
    same package. Make the constructor of the TO
    protected (or package private). Then, the DAO can
    initialize values from the persistent store, but
    users of the TO will only be able to read thevalues
    retrieved. If this model becomes limiting, you
    should realize that you are now allowing mutator
    methods. IMO, your TO should now be afully-fledged
    domain model object.
    I disagree. And apparently others do as well because
    your model is the way that J2EE first represented
    DTOs (as a "Value Object").
    I will refer you to Bloch, et. al. Immutable objects are easier to code and to test.
    I suppose my reason for this would be that most of
    the work in other layers involves sending mutated
    data back. With your pattern this requires that the
    user, every single time, create a new object, copy
    the old data to the new, and then send the new object
    back.
    You are asserting the 'new' keyword is onerous?
    Extra work with no gain.
    I agree. There is an ever so slight overhead to creating a new, immutable object. However, limiting the possible states of an object, by definition, lowers its entropy and hence the possibilities one needs to test.
    The DAO can only have four methods, create,read,
    update and delete. I am a little confused here,
    because as I see it, we can only have thesefour
    methods to read/write from/to the TO.
    This is roughly what a database allows. However,
    what of commonly used parent-child or foreign-key
    relationships? You may retrieve an account holder
    and his/her present balance 90% of the time inyour
    system. Do you want two separate TO's and DAO's
    here? Or is this a case where a DAO can constructa
    graph of objects in memory as an optimization?
    Yes. Issuing a single SQL query to fetch a parent child relationship is more efficient than fetching foreign keys in a parent table and querying for each child. Maybe we are in fact on the same page, maybe not. But I am referring to releationships such as many-to-many that pose difficulties to O/R mappers. The same would hold true for a design where each table row corresponds to an object.
    There are several other J2EE patterns for complex
    relationships.
    I am not sure I have ever encountered a need for
    those though.
    Other than chaining various Collection classes, neither have I. However, a fairly rich set of relationships (hierarchical, sequential, dependent, etc.) can be constructed from these.
    >>
    This would cause difficulties if we wanted to
    implement optimistic locking for example, wherewe
    wanted to check if a row had been changed before
    commiting the change (to prevent lost updates).
    I would not implement this myself. As Duffy has
    alluded to, Hibernate and other O/R mapping
    technologies maintain the state of an object andthe
    state when it was retrieved, allowing theframework
    to update only modified fields when needed.
    Interesting.One of the best benefits that Hibernate offers out of the box, that and lazy loading. Though like all things, these too can be abused.
    - Saish

Maybe you are looking for

  • Safari and itunes won't open

    I was using my mac 3 days ago and everything was fine, then comcast had a internet problem and I lost service for 3 days now I have internet but safari and itunes won't open the icon bounces once and then nothing. I have removed them from the dock, a

  • Problems with Ken Burns effect

    Having a very frustrating time trying to get a decent slideshow. Like the KB effect but when I play it back the images jerk and jump. Smoothness totally gone. Strange thing is sometimes it is worse than others. Have tried closing all other unnecessar

  • Can't download pdf and xls file

    Hi, I want to download an attachment from my gmail .When I clicked to download, it will go to icloud.com and displayed like this."Your file will begin downloading automatically.Don't see it? Try again> The attachment contains both pdf and xls files.

  • Click on email not heard (sometimes) after 10.7.2 update

    I've noticed that since I did the recent Lion update to 10.7.2 that when I'm in Mail (the new interface, not classic) that SOMETIMES when I click on a email in my message list that it does not pop into the view pane. Sometimes it is heard, other time

  • Nearly all fonts appear the same in Mail; otherwise they show up VERY tiny

    Is there a setting in Mail that turns the font size down several levels? Because when I try a font in Word and then in Mail, it shows on my screen in Mail less than 1/2 the size it does in Word. Same font. Same point size. Bold & italic dont seem to