Using DAO without J2EE/EJB

Can I implement the DAO pattern in my 2-tiered application without using J2EE/EJB? My reason for using DAO is simply to insulate database changes from interface/business code and to make interface/business code easier to write.

Sure, go ahead.

Similar Messages

  • Using mdb without other ejbs

    I have a message queue(with some XML files) and i am trying to write a mdb so that it can access that asynchronously and pass it to another java class for further processing.
    My project is not using EJB and i am not so proficient in ejbs.
    I DO NOT want to use any of those bmp or cmp but only mdb.I am still not able to get the exact design.Should i pass the data from mdb to servlet or from mdb directly to my model class.
    Most of the info suggest/show examples of mdb along with session/entity beans.Can mdb function without other ejbs (except ejb container)?
    Can someone suggest the best practices based on the above requirements? Sample code would be appreciative.
    Regards,
    Gyan

    A MDB is essentially a piece of code that is automatically executed when a message is received from a JMS queue or topic. You can invoke a session bean from a MDB but you don't have to. You can do all the message processing in the MDB if you want to. You could, for example, transform the data, send another message, and write to a database, all from within the MDB.
    A Servlet is essentially a piece of code that is automatically executed when a HTTP request (usually a GET or POST) is received, typically (but not necessarily) from a web browser.
    You wouldn't normally invoke a servlet directly from a MDB, although it would be technically possible. More common is to do the oppsite, have a servlet that receives a HTTP request, extracts the information, and writes it to a JMS queue. A little later a MDB receives this message and processes it.
    It might be worth reviewing the Java EE 5 tutorial at
    http://java.sun.com/javaee/5/docs/tutorial/doc/index.html
    especially the section on message-driven beans.
    (there's also a tutorial for java EE 6).
    Nigel

  • Using JTA without an EJB server

    Hi,
    What is the most popular way of using JTA without EJB.
    I notice there is:
    JOTM?
    Is this the one?
    Cheers

    beginner2 wrote:
    Hi,
    What is the most popular way of using JTA without EJB.
    I notice there is:
    JOTM?
    http://jotm.objectweb.org/
    Is this the one?
    Cheerssure. that's one way.
    %

  • How to use mysql in J2EE server?

    Hi all,
    I have been learning J2EE and playing around with Pointbase as my database and the IDE that I'm using is Forte For JAVA 4 EE.
    Now, I wanna use mysql in J2EE, EJB. But I do not know how to use mysql in j2ee server. I have try to altered the resources.property file by adding a few lines to called the MYSQL datasource and driver. But, it give me errors when i am doing the deployment process. Can any1 of u help me?
    Thanks in advance..

    Hi,
    I guess there must be some problem with your App Server Configuration settings:
    Kindly Check if you are using the following ones:
    Driver Name: com.mysql.jdbc.Driver
    Url: jdbc:mysql://[hostname][,failoverhost...][:port]/[dbname][?param1=value1][&param2=value2].....
    Thanks & regards,
    Paritosh
    Software Engineer
    L&T Infotech Ltd

  • Where to Instantiate a DAO in an EJB BMP?

    We are using DAOs with our EJB BMPs..
    My question is what method should the DAO be Instantiated in?
    I have seen it done in the:
    1) ejbActivate (seems to cause a null pointer error on the weblogic server)
    2) setEntityContext method
    3) all methods that use the dao object.

    This depends a bit on how your DAOs are built, but you certainly don't want to instantiate a new DAO every time you need one. Unnecessary object creation is not a Good Thing.
    Generally speaking, an instance variable populated upon bean instantiation works just fine (i.e private MyDao dao = new MyDao();). If your DAO is serializable and doesn't contain any transient info of it's own, you're pretty much done since the DAO will get serialized when the bean is passivated.
    If it does contain transient data/resources (and it probably shouldn't) you can set/remove them during ejbActivate/ejbPassivate.
    If the DAO is not serializable (and it probably should be), then instantiating one during ejbActivate should not be a problem. What was the exact cause of the NPE you got?

  • Using J2EE EJB Container and Oracle 8.1.7

    I am trying to setup the J2EE EJB container to use and Oracle 8.1.7 database instead of Cloudscape. So far I have done the following
    0. Created the table for the Savings Account tutorial in the Oracle Database.
    1. Added the Classes12.jar (Oracle's latest JDBC thin drivers) to my CLASSPATH
    2. Under "Server Configuration" I added the standard/jdbc drivers value: "oracle.jdbc.driver.OracleDriver".
    3. Under "Server Configuration" I added the standard/datasource value: JNDI name "jdbc/Oracle" and JDBC URL "jdbc:oracle:thin:@10.1.1.254:1521:DEV".
    4. For the savings account tutorial, when deploying I specified "jdbc/Oracle" for the reference "jdbc/SavingsAccountDB".
    I have gotten this tutorial to work using the Cloudscape database. After I did the previous steps and tried to run the client, I get no valid driver available, unable to connect to Oracle.
    What else to I need to do?
    My setup is:
    Windows 2000 Professional
    J2EE (JDK 1.3.1)
    Oracle 8.1.7
    Thank you in advance.

    Exactly which classpath did you add the Oracle JDBC library jar to ?
    The thing that works for me is to have the following line in the file %J2EE_HOME%\bin\userconfig.bat
    set J2EE_CLASSPATH=D:\DownLoad\Oracle\classes12_01.zip;

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

  • Using DAO using a JDBC data source with struts

    Hello,
    I have created a number of Data Access Objects and Transfer Objects to use in a non EJB, struts web application I am developing. I had tested these with a kind of a Service Locator custom class to provide access to a JDBC connection. My custom class is a bit clunky and not very configurable. I would like to use a data source using the struts config XML file e.g.
        <data-sources>
            <!-- configuration for commons BasicDataSource -->
            <data-source type="org.apache.commons.dbcp.BasicDataSource">
                <set-property
                  property="description"
                  value="My MySQL Database Connection" />
                <set-property
                  property="driverClassName"
                  value="com.mysql.jdbc.Driver" />
                <set-property
                  property="url"
                  value="jdbc:mysql://localhost/databaseName" />
                <set-property
                  property="username"
                  value="myUsername" />
                <set-property
                  property="password"
                  value="xxxxxxxxx" />
                <set-property
                  property="maxActive"
                  value="10" />
                <set-property
                  property="maxWait"
                  value="5000" />
                <set-property
                  property="defaultAutoCommit"
                  value="false" />
                <set-property
                  property="defaultReadOnly"
                  value="false" />
             </data-source>
        </data-sources>This is great, and precisely the kind of thing I would like to use. However, this datasource is only available AFAIK through a HttpServletRequest instance like in the example I found below...
        public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                     HttpServletResponse response)     throws Exception
            javax.sql.DataSource dataSource = null;
            java.sql.Connection myConnection = null;
            try {
             dataSource = getDataSource(request);
             myConnection = dataSource.getConnection();
             // do what you wish with myConnection
            } catch (SQLException sqle) {
               getServlet().log("Connection.process", sqle);
            } finally {
               //enclose this in a finally block to make
               //sure the connection is closed
               try {
                  if(myConnection != null)
                      myConnection.close();
               } catch (SQLException e) {
                  getServlet().log("Connection.close", e);
            return (mapping.findForward("success"));
        }That would be great if I wanted to use the database connection anywhere near a struts Action (wrong tier!). I want access like that to to a data source in my DAOs. Is it possible for me to use the data-sources aproach to access the DB from my DAOs or will I need to use something like JNDI to do this in a similar way but separate from struts. If so I have a big gap in my knowledge as far as JNDI goes which I need to fill and that will be my next question
    I'm relatively new to using patterns inn Java and any help or pointers would be great.
    Thanks :)

    Create a JAAS Authentication Entry in the Server configuration.
    This should then appear in the drop-down when specifying your DataSource.

  • Changing a method in an EJB object without recompiling EJB-Clients

    Hi!
    I have 4 Web (JSP) applications using the same EJBs., deployed to a BEA Weblogic application server.I want to know if there is a way to change the code in a method in one of my EJB objects (no interface change) without recompiling and redeploying my EJB-clients and Web apps.
    Regards,
    Per - Chr.

    Hello,
    I have 4 Web (JSP) applications using the same EJBs.,
    deployed to a BEA Weblogic application server.I want
    to know if there is a way to change the code in a
    method in one of my EJB objects (no interface change)
    without recompiling and redeploying my EJB-clients and
    Web apps.You can change the EJB's without recompiling the clients as long as the interfaces and the classes used by both the EJB's and clients are not changed.
    For example, if you don't change the interfaces but change the exception implementation thrown by a method of the bean, then you have to recompile the clients with the new version of the exception class.
    Kexkey

  • ERROR J2EE EJB-03027 with OC4J 10.1.3.3

    Hi,
    we have an application that works fine in iAS 9i (9.0.3).
    Now, we have to migrate the platform to 10G and we are testing with OC4J 10.1.3.3.
    But when the OC4J works... we see this message:
    2008-03-06 16:10:12.737 ERROR J2EE EJB-03027 [prueba] Se ha producido un error al desplegar el módulo EJB: java.lang.InstantiationException: Internal server error: oracle.classloader.util.AnnotatedClassFormatError (Bad version number in .class file
         Clase no válida: UPHome_EntityHomeWrapper1
         Cargador: prueba.root:0.0.0
         Origen de Código: /C:/OC4J 10.1.3.3/j2ee/home/application-deployments/prueba/MGU-1.0/deployment-cache.jar
         Configuración: <ejb> in wrappers
         Clase Dependiente: com.evermind.server.ejb.deployment.EntityBeanDescriptor
         Cargador: oc4j:10.1.3
         Origen de Código: /C:/OC4J 10.1.3.3/j2ee/home/lib/oc4j-internal.jar
         Configuración: <code-source> in META-INF/boot.xml in C:\OC4J 10.1.3.3\j2ee\home\oc4j.jar
    08/03/06 16:10:12 ADVERTENCIA: Application.setConfig Application: prueba is in failed state as initialization failed.
    java.lang.InstantiationException: Error initializing ejb-modules: Internal server error: oracle.classloader.util.AnnotatedClassFormatError (Bad version number in .class file
         Clase no válida: UPHome_EntityHomeWrapper1
         Cargador: prueba.root:0.0.0
         Origen de Código: /C:/OC4J 10.1.3.3/j2ee/home/application-deployments/prueba/MGU-1.0/deployment-cache.jar
         Configuración: <ejb> in wrappers
         Clase Dependiente: com.evermind.server.ejb.deployment.EntityBeanDescriptor
         Cargador: oc4j:10.1.3
         Origen de Código: /C:/OC4J 10.1.3.3/j2ee/home/lib/oc4j-internal.jar
         Configuración: <code-source> in META-INF/boot.xml in C:\OC4J 10.1.3.3\j2ee\home\oc4j.jar
    We have looked for information about the 'Bad version number' error, and we have recompile all our code with the JDK 1.5 (the same JDK for the OC4J). But we still have the error...
    Which may be the problem?...
    Thanks.

    The only thing you can do is to make sure that you recompile everything you're using.
    --olaf                                                                                                                                                                                           

  • Can I use static variable in EJB?

    Many books suggest developer don't use static variable in EJB,I want to know why?
    I know there isn't any problem if the static varibale is read only
    For writable static varible ,what will happen if I use a static Hashtable for share data
    Help me!Thank you very much!!

    Greetings,
    I know that "EJB business methods are not allowed to
    block on synchronized resources" Just where do you "know" that from?? The EJB 2.0 Specification, at least, is nowhere in agrement with this statement. If it comes from a book I would question the author's reasoning. Contractually, there's no sound basis for this. In the case of Session Beans, they have an expressedly direct and single-threaded association with a client. From a design viewpoint, it certainly seems unnecessary for a bean to "block" its one-and-only client, but to say that it "is not allowed to" do so is without merit. Entity Beans, on the other hand, are concurrently accessible. Yet, with regard to a transactional context being in effect, the container does indeed block on a bean's business methods. For the bean to do so itself is, therefore, unnecessary. Furthermore, the specification explicitly concedes that a "Bean Provider is typically an application domain expert" and "is not required to be an expert at system-level programming." (EJB 2.0 Spec. 3.1.1) From these statements alone it is reasonable to assume the above statement is meritless since the Bean Provider is not expected to even consider synchronization issues when developing a bean.
    But I'm mixed up why we could use "Hashtable" or otherApparently, because your sources are as well...
    collection classes in the EJB ,in these method many
    methods are synchronized In fact, not only "can we use" them but, with respect to multiple-row finders in Entity Beans we are [i]required to use them (or an iteration of them)! Not all Collection classes are synchronized (so called "heavy-weight collections"). As shown above, that the choice of a particular Collection class might be synchronized is of little consequence since a bean designed under strict adherence to the specification ensures that it is never concurrently writeable.
    Could someone provide a good way for this problem?
    Please Help Me!!!Regards,
    Tony "Vee Schade" Cook

  • How I use DAO

    I built a struts application .It is working well.Now I want use DAOand .How I use?
    My struts application :
    Get the input form user and store it in file or datadase. Here I want to use DAO.
    There 6 files .
    They are
    1.inputname.jsp ----------->used for getting input from client.inputs are mail id and password.
    2.GetNameForm.java --------->It is Bean having setter and getter including 2 methods are like filehandler(),dbConnection()(here only implementations).
    dbConnection method just sample i did. From MSAccess database, get Age field and print it in tomcat prompt. Here only i have probs.*What probs that I need to use DAO.
    3.GreetingAction.java ------>It is servlet and I call FormBean Method
    By ((sample.GetNameForm)form).filehandler();
    ((sample.GetNameForm)form).dBConnection();
    String name=((sample.GetNameForm)form).getName();
    String pass=((sample.GetNameForm)form).getPass();
    Thus I called that methods.
    It is good one or Not.
    Note. Both java file under the package name is sample.
    4.greeting.jsp--------> It is output file which is used to expose the output that mail id and password what we gave.
    5.index.jsp---------->It is global forward used to forward client request to inputname.jsp.(It is not a matter to consider with out this file applkication working well.)
    5.struts-config.xml file here only direction controls and mapping items and brief links (we know that).
    package sample;
    import java.io.*;
    import java.sql.*;
    import javax.servlet.http.HttpServletRequest;
    import org.apache.struts.action.ActionError;
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.ActionMessage;
    public class GetNameForm extends org.apache.struts.action.ActionForm {
    private String name="";
    private String pass="";
    public GetNameForm() {
    // TODO: Write constructor body
    public void reset(ActionMapping actionMapping, HttpServletRequest request) {
    // TODO: Write method body
    // throw new UnsupportedOperationException("Method not implemented");
    this.name="";
    this.pass="";
    public ActionErrors validate(ActionMapping actionMapping, HttpServletRequest request) {
    // TODO: Write method body
    //throw new UnsupportedOperationException("Method not implemented");
    ActionErrors errors=new ActionErrors();
    if( getName() == null || getName().length() < 1 ) {
    errors.add("name",new ActionMessage("error.name.required"));
    // actionMapping.findForward("goInput");
    if( getPass() == null || getPass().length() < 1 ) {
    errors.add("pass",new ActionMessage("error.pass.required"));
    // actionMapping.findForward("goInput");
    return errors;
    public String getName()
    return this.name;
    public void setName(String name)
    this.name=(name==null?"Please Enter The Name":name);
    public String getPass()
    return this.pass;
    public void setPass(String pass)
    this.pass=(pass==null?"Please Enter The ID":pass);
    public void dBConnection()
    Statement st;
    Connection con;
    ResultSet rs;
    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    catch(Exception e)
    try
    con=null;
    st=null;
    rs=null;
    con=DriverManager.getConnection("jdbc:odbc:MSACCESSDSN","","");
    st=con.createStatement();
    rs=st.executeQuery("Select * from emp ");
    while(rs.next())
              int a=rs.getInt("Age");
              System.out.println(a);
    catch(Exception e)
    public void filehandler() throws IOException
    String name=getName();
    String pass=getPass();
    //Store the Details of User and Password in File
    Writer output = null;
    try {
    //use buffering
    File testFile = new File("C:\\gandhi\\mail_det.txt");
    BufferedReader input = null;
    input = new BufferedReader( new FileReader(testFile) );
    StringBuffer Contents=new StringBuffer();
    String line=null;
    while (( line = input.readLine()) != null)
    {System.out.println("From the file value=" +line);
          java.util.StringTokenizer st = new java.util.StringTokenizer(line,"@");
          System.out.println("The file contains data:"+Contents.append(line+"\n"));
         /* System.out.println(st.nextToken("@"));
          while (st.hasMoreTokens()) {
                if( st.equals("name") ){
                name="";
                pass="";
    String str=Contents.toString();
    System.out.println("The file Contains"+str);
    output = new BufferedWriter( new FileWriter(testFile) );
    output.write(str+"\n"+name+"\t"+"........."+pass);
    finally {
    //flush and close both "output" and its underlying FileWriter
    if (output != null)
    output.close();
    This is my Bean How I use DAO replace of dBConnection()
    method.
    1.What is important of DAO pls explain me with small codings.
    2.How I use DAO in this coding?
    [Note: I use Exadel StrutsStudio.]
    Anyone have idea pls guide me.

    Well in a DAO pattern you usually have one DAO class for each table in the database so there is for instance one PersonDAO and one ItemDAO which have their respective create, read, update and delete methods. Each DAO also hides its implementation through an interface defining the DAO methods, furthermore there's a DAO factory determining what class to load at runtime. My advice is to start out simple and not too abstract, try looking at the following example - it involves EJBs but explains the pattern.
    http://www.informit.com/guides/printerfriendly.asp?g=java&seqNum=137&rl=1
    Also keep in mind that implementing the DAO pattern using frameworks such as Spring simplifies the process, as illustrated here
    http://www.java2s.com/Code/Java/Hibernate/SpringDaoDemo.htm
    I hope that helps.

  • Using COM component from EJB

    Hi,
    I'd like to use a third party COM component from. I know JIntegra and such tools but I'd like to use a non-commercial software as I need it for my diploma thesis.
    Did anyone ever manage to call an ActiveX/COM component from an EJB. I mean a third party component, not a self developed one.
    Could I use M$ specific classes in my EJB or do they rule out each other?
    Any working example?
    TIA
    Frank

    Did you really manage to use third party DLLs with EZJCOM?
    Would be great if you could clarify this to me:
    If I would use M$ specific classes to have a Java / COM - communication then I would
    have to use M$ JVM, right?
    But if I use that VM, I can not use my classes within the J2EE / EJB environment as this
    requires Sun's JVM, right?
    So, if I use EZJCOM for that than I do not have to use any M$ specific stuff, right?
    Unfortunately, I did not get any further yet. The product I'd like to use is Lindo.
    I have the DLL, but trying to use it with EZJCOM it says: No COM interface definition.
    No tlb is given either. There's a JAR package with classes that seem to use JNI to call
    DLL functions, so maybe it does not provide a COM interface.
    But that means I would have to build my own (maybe VB) ActiveX DLL that calls all the funtions
    in the Lindo DLL. But that would keep me busy for weeks I guess :-(
    As I need it for my diploma thesis, I can not spend a lot of time building ActiveX components.
    Frank

  • Authentication using database in j2ee ri server? URGENT!!

    Hello I have installed j2sdkee1.3.1 and I use the web and ejb server that it includes. I start it with j2ee.bat and I create a application with jsp and ejb, and I use deploytool to deploy it. I don't have problem, but now I would like to use a form-based autentication. I config it in deploytool but I want that the j2ee server access to a database to check if a user have the role that he need to access. I do this with the option of deploytool in which you can add users and roles, but I don't know how to config it for a database.
    In tomcat4.1 you can do this adding the next lines to server.xml:
    <Realm className="org.apache.catalina.realm.MemoryRealm" />
    <Realm className="org.apache.catalina.realm.JDBCRealm" debug="99"
    driverName="com.jnetdirect.jsql.JSQLDriver"
    connectionURL="jdbc:JSQLConnect://localhost/database=name"
    connectionName="user" connectionPassword="pass"
    userTable="user" userNameCol="usuario" userCredCol="clave"
    userRoleTable="userRol" roleNameCol="rol" />
    I want to use only the j2ee server. I config it in j2sdkee1.3.1\conf\server.xml adding the next lines, as I do with Tomcat but here in j2ee it isn't.
    I don't know why j2ee server doesn't use this file, or how I have to config it to use a database to autenticate.
    It's very urgent.
    Thanks for all and sorry for my english I'm spanish.

    Hi Moi,
    j2ee1.3.1 is not supported any more. Please try j2ee1.4beta2.
    Regards,
    -- markus.

  • How to open document from mac when using windows without transferring the file?

    How can i open a document from mac when i am using windows without transferring it?

    depend on the document program more then anything else really
    when ever I open a doc with word it make a history for undo and redo action file in the same dir
    with bootcamp you only have read not write access to the osx partition so it would fail to be able to create that file
    but if you can get word or whatever program you use to open the file not to place a temp file in the same dir
    or use a program which did not make any type of temp file or used a program where the temp file would be located elsewhere where you decide it would work file

Maybe you are looking for

  • My matchbook pro keeps restarting

    I find this below kernel message while my matchbook pro restarts? i changed my old Hard-disk and installed new one, the problem was solved for a while then it appeared back again. when it restarts i find my screen the same before it restarts as if it

  • Regarding back ground job scheduling

    Hi,     one of our program was sheduled for back ground job, by another user, so just i need to knwo when this job is sheduled and it is executing daily, so, i need to knwo whether he has created a background job through , sm36, or through a program,

  • Business Components for Java - Pooling

    I need a little bit of clarification regarding business components for java... I would like to create a jdbc connection pool for my application to avoid the overhead of creating new jdbc connections each time a client connects. Since I'm using BC4J,

  • Hello, I'm having some problems with caller ID

    Hi I've just got a blackberry pearl from a friend (which I love!!) but am having problems with the ID when I receive texts and calls. The text messages ID's come up as numbers (eg +447789*******) rather than the persons name. So I changed all the num

  • Adobe Flash versus HTML 5

    Hi, I allways liked Adobe Flash for websites but I wonder if it's a good descission to use it these days. Many vendors for tablets and smartphones do not support it. I'm currently setting up an online busines (http://multimediareviews.net) but I'm he