Static methods in data access classes

Are we getting any advantage by keeping functions of DAOs (to be accessed by Session Beans) static ?

I prefer to have a class of static methods that
require a Connection to do their work. Usually, there
is a SessionBean that 'wraps' this DAO. The method
signatures for the SSB are the same, minus the need
for a Connection, which the SSB gets before delegating
to the Static Class.Uggh, passing around a connection. I've had to refactor a bunch of code that used this pattern. We had classes in our system that took a class in their constructor simply because one of their methods created an object that needed the connection. Bad news--maintenance nightmare--highly inflexible.
What we've done is create ConnectionFactory singletons that are used throughtout the application in order to get connections to the database. All connection factory implementations implement the same interface so they can be plugged in from other components at runtime.
In my opinion, classes that use connections should manage them themselves to ensure proper cleanup and consistent state. By using a factory implementation, we simply provide the DAO classes the means by which they can retrieve connections to the database and even the name of the database that needs to be used that is pluggable. The DAO classes do their own connection management.
For similar reasons, I eschew the static method concept. By using class methods, you make it difficult to plug in a new implementation at runtime. I much prefer the singleton pattern with an instance that implements a common interface instead of a class full of static methods.
I recently needed to dynamically plug in new connection factory implementation so that we could use JNDI and DataSources within the context of the application server (pooled connections) but use direct connections via the Driver manager for unit testing (so the application server didn't need to be running). Because of the way this was coded, I simply changed the original factory to be an abstract factory and changed the getInstance() method to return a different implementation based on the environment (unit test vs live). This was painless and didn't require changing a single line of client code.
If I had to do this using the previous code that I refactored, I would have had to change about 200 jsp pages and dozens of classes that were making calls to the static method of the previous factory or hacked in something ugly and hard to maintain.
YMMV

Similar Messages

  • Urgent: how to really seperate business logic class from data access class

    Hello,
    I've this problem here on my hand and i really need help urgently. so please allow me to thank anyone who replies to this thread =)
    Before i go any futhur, let me present a scenario. this will help make my question clearer.
    "A user choose to view his account information"
    here, i've attempted to do the following. i've tried to seperate my application into 3 layers, the GUI layer, the business logic layer, and the data access layer.
    classically, the GUI layer only knows which object it should invoke, for example in the case above, the GUI would instantiate an Account object and prob the displayAcctInfo method of the Account object.
    here is how my Account class looks like:
    public class Account
    private acctNo;
    private userid;
    private password;
    private Customer acctOwner;
    the way this class is being modelled is that there is a handle to a customer object.
    that being the case, when i want to retrieve back account information, how do i go about retrieveing the information on the customer? should my data access class have knowledge on how the customer is being programmed? ie setName, getName, setAge, getAge all these methods etc? if not, how do i restore the state of the Customer object nested inside?
    is there a better way to archieve the solution to my problem above? i would appriciate it for any help rendered =)
    Yours sincerely,
    Javier

    public class AccountThat looks like a business layer object to me.
    In a large application the GUI probably shouldn't ever touch business objects. It makes requests to the business layer for specific information. For example you might have a class called CustomerAccountSummary - the data for that might come entirely from the Account object or it might come from Account and Customer.
    When the GUI requests information it receives it as a 'primitive' - which is a class that has no behaviour (methods), just data. This keeps the interface between the GUI and business layer simple and makes it easier to maintain.
    When using a primitive there are four operations: query, create, update and delete.
    For a query the gui sets only the attributes in the primitive that will be specifically queried for (or a specialized primitive can be created for this.) The result of a query is either a single primitive or a collection of primitives. Each primitive will have all the attributes defined.
    For a create all of the attributes are set. The gui calls a method and passes the primtive.
    For an update, usually all fields are defined although this can vary. The gui calls a method and passes the primitive.
    For a delete, only the 'key' fields are set (more can be but they are not used.) The gui calls a method and passes the primitive.
    Also keep in mind that a clean seperation is always an idealization. For example verify that duplicate records are not created is a business logic requirement (the database doesn't care.) However, it is much easier and more efficient to handle that rule in the database rather than in the business layer.

  • In terms of scalabilty, will static method in normal java class better than

    You only have one copy of the static method in memory, but you have a few copy of the stateless session bean, plus the overhead of those session bean.So isn't static method of normal java class more scalable than stateless session bean.

    Then you have to take care of transaction management, connection pooling, etc other ejb services all by your self.
    In fact stateless session beans acts more like a static class. They do not get destroyed when remove() method is called on client stub. Similarly they are not always gets created whenever someone calls create() method on home interface!! (Again it's specific to appserver implementation)
    Thx.

  • Can we call a static method without mentioning the class name

    public class Stuff {
         public static final int MY_CONSTANT = 5;
         public static int doStuff(int x){ return (x++)*x;}
    import xcom.Stuff.*;
    import java.lang.System.out;
    class User {
       public static void main(String[] args){
       new User().go();
       void go(){out.println(doStuff(MY_CONSTANT));}
    }Will the above code compile?
    can be call a static method without mentioning the class name?

    Yes, why do it simply?
    pksingh79 wrote:
    call a static method without mentioning the class name?For a given value of   "without mentioning the class name".
        public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws Exception {
            Class<?>[] types = new Class<?>[args.length];
            for(int i=0;i<args.length;++i) types[i] = args==null?Object.class:args[i].getClass();
    return Class.forName(className).getDeclaredMethod(methodName,types).invoke(null,args);

  • Data Access Class Reading a Text File????

    Hi,
    I have created a data access class... and for one of my constructors.. I need to go a text file and get the information : dsn name, username, and password from the file and bring it into the construtor... does anyone know how to do that??
    Thx
    Rich
    Here is my constructor:
    public DataAccess() {
    }

    Define a PropertyManager class where you specify the file and read the parameters? I have a sample I will have searc through my archive.
    Will post if after some time.
    Hope I gave a small spark to ignite.
    Cheers.
    Sekar.

  • Generic static methods in a parameterized class

    Is there anything wrong with using generic static methods inside of a parameterized class? If not, is there anything special about defining them or calling them? I have a parameterized class for which I'd like to provide a factory method, but I'm running into a problem demonstrated below:
    class MyClass<T> {
         private T thing;
         public
         MyClass(T thing) {
              this.thing = thing;
         public static <U> MyClass<U>
         factoryMakeMyClass(U thing)     {
              return new MyClass<U>(thing);
    class External {
         public static <U> MyClass<U>
         factoryMakeMyClass(U thing)     {
              return new MyClass<U>(thing);
    class Test {
         public static void
         test()
              // No problem with this line:
              MyClass<String> foo = External.factoryMakeMyClass("hi");
              // This line gives me an error:
              // Type mismatch: cannot convert from MyClass<Object> to MyClass<String>
              MyClass<String> bar = MyClass.factoryMakeMyClass("hi");
    }Does this code look ok to you? Is it just a problem with my ide (Eclipse 3.1M2)? Any ideas to make it work better?

    I've been working on essentially the same problem, also with eclipse 3.1M2. A small variation on using the external class is to use a parameterized static inner class. I'm new enough to generics to not make definitive statements but it seems to me that the compiler is not making the correct type inference.
    I think the correct (or at least a more explicit) way of invoking your method would be:
    MyClass<String> bar = MyClass.<String>factoryMakeMyClass("hi");
    See http://www.langer.camelot.de/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ401
    See http://www.langer.camelot.de/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ402
    Unfortunately, this does not solve the problem in my code. The compiler reports the following error: The method myMethod of raw type MyClass is no more generic; it cannot be parameterized with arguments <T>.
    Note that in my code MyClass is most definitely parameterized so the error message is puzzling.
    I would like to hear from more people on whether the sample code should definitely work so I would appreciate further comments on whether this an eclipse problem or my (our) misunderstanding of generics.     

  • Confusion... Data Access Object and Collection Class

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

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

  • Static methods and how to access

    Hi,
    This seems like a silly quesion but i am trying to access a static method but it tells me that i cant.
    The method i am calling from is not static
    Thanks

    syntax: class name dot static method name (assuming the method is accessible): StaticMethodClassName.aStaticMethod();
    can't reference a class member (variable, object, method, ...) from a static method because a static method is not a class member (it is simply a method whose scope is confined to that of the class in which it is defined).
    example:
    class Foo
    int i;
    public static void hasSyntaxErr() // this method is not a member of Foo
    i = 0; // not allowed because i is a member of Foo
    class Fooo
    void testStatic() { Foo.hasSyntaxErr(); }
    }

  • When a static method is accessed concurrently

    When a static method is accessed by many objects symultaneously(concurrently),
    What is happened in the static method.
    Are the stacks for that method maded seperately and
    each stack doesn't influence other stacks?
    thank you in advance.

    The static objects or methods concept is clear, one
    instance for all objects.No. One instance for the class.
    , and every
    one know that, static methods is slower than
    nonstatic, Since when? I've certainly never heard that before... Do you have a reference I can look at?
    and this is as i thought because static
    methods are syncronized by default.Absoloutely not!
    All synchronization locks on an object. When you synchronize an instance method, it locks on the implicit "this"; When you synchronize a static method, it locks on the class's associated Class object.
    So two synchronized static methods in the same class can not be called at the same time, but synchronized instance methods that access static variables can all access those variables at the same time and potentially cause threading problems. In this situation you can declare the static fields volatile or wrap synchronized blocks around all code that accesses them, and synchronize on the same object (perhaps the Class object associated with the current class would be appropriate, but that reallt depends on the rest of your design).

  • Accessing Class Methods

    I am working on a little project and am at a sticking point.
    What I want to do is access a method that resides in the class that contains the "main" method. I want to access the method from another class. So, I do not want to instantiate another of that class because that opens another "copy" of the program. I just want to access a method in that class.
    Is there a way to do this?
    Thanks for any assistance.
    Mike

    how do I add an actionListener to a component that is declared static
    inside the static method....cannot use "this" keyword?What do you mean declared static inside a static method? To the best of my knowledge, the only modifier (if that's the correct term) you can apply to variable declarations within methods (static or not) is final.
    Anyway, taking a guess at what you want:
    public class Main {
        private static final Component x = ;
        public static final main(final String[] args) {
            x.addActionListener(new ActionListener() {
                public void actionPerformed(final ActionEvent e) {
                    magicMethod();
        private static void magicMethod() {
    }While you can't call an instance method from a static method (without having an instance) you can do the reverse. In this case, I'm not even doing the reverse, I'm calling a static method from an anonymous class instance declared within a static method.

  • Compilation error while calling static method from another class

    Hi,
    I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
    In Dummy1.java I have declared a static final variable and a static method as you can see it below.
    package Test;
    import java.io.*;
    public class Dummy1
    public static final int var1= 10;
    public static int varDisp(int var2)
    return(var1+var2);
    This is program is compiling fine.
    I have called the static method varDisp from the class Dummy2 and it is as follows
    package Test;
    import java.io.*;
    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    and when i compile Dummy2.java, there is a compilation error <identifier > expected.
    Please help me in this program.

    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    }test+=Dummy1.varDisplay(var3);
    must be in a method, it cannot just be out somewhere in the class!

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Abstract class and a static method

    Can i call a static method within an abstract class ?

    public class AbstractDemo {
      public static void main(String[] args) {
        BiPlane biPlane = new BiPlane();
        System.out.println("biplane propulsion = " + biPlane.getPropulsionType());
        JumboJet jumboJet = new JumboJet();
        System.out.println("jet load = " + jumboJet.confirmMaxLoad());
        System.out.println("jet speed = " + jumboJet.getTopSpeed());
        System.out.println(Airplane.confirmMaxLoad());
    abstract class Airplane {
      static String confirmMaxLoad() {
        return "go_get_um, yeehaa!";
      public abstract String getPropulsionType();
      abstract String getTopSpeed();
    class BiPlane extends Airplane {
      public BiPlane() {
        System.out.println("BiPlane constructor");
      static String confirmMaxLoad() {
        return "400 lbs";
      public String getPropulsionType() {
        return "propeller";
      final String getTopSpeed() {
        return "130 knots";
    class JumboJet extends Airplane {
      public JumboJet() {
        System.out.println("JumboJet constructor");
      public String getPropulsionType() {
        return "jet";
      public String getTopSpeed() {
        return "mach .87";
    }

  • Why do we need private static method or member class

    Dear java gurus,
    I have a question about the use of private and static key words together in a method or inner class.
    If we want to hide the method, private is enough. a private static method is sure not intended to be called outside the class. So the only usage I could see is that this private static method is to be called by another static method. For inner class, I see the definition of Entry inner class in java.util.Hashtable, it is static private. I don't know why not just define it as private. Could the static key word do anything better.
    Could anybody help me to clear this.
    Thanks,

    What don't you get? Private does one thing, andstatic does >something completely different.
    If you want to listen to music, installing an airconditioner doesn't help>
    Hi, if the private keyword is the airconditioner, do
    you think you could get music from the static keyword
    (it acts as the CD player) in the following codes:You're making no sense and you're trying to stretch the analogy too far.
    Private does one thing. If you want that thing, use private.
    Static does something completely different and unrelated. If you want that thing, use static.
    If you want both things, use private static.
    What do you not understand? How can you claim that you understand that they are different, and then ask, "Why do we need static if we have private"? That question makes no sense if you actually do understand that they're different.

  • Why can't inner classes have static methods?

    I just tried to add a static method to an inner class, which would have been useful for extracting constants about said inner class, and it turns out that is not allowed.
    Of course I have other ways to code what I wanted, but I'm curious as to why this restriction was set in place. Anybody know?

    Probably because an inner class is tied to an instance of the enclosing class. I think that, conceptually at least, the inner class' definition itself only exists in the context of an instance of the enclosing class. While I'm sure it would have been technically possible to allow it, it would be confusing and not make a whole lot of sense--what is the static context for the inner class, since the class only exists in a non-static context?

Maybe you are looking for

  • Reading a font file from url

    I am trying to read font files on a server to create fonts. here is the url of the font file. http://localhost/myapp/fonts/arial.ttf I am using Font.createFont(Font.TRUETYPE_FONT, XXX ); method but I can't get a proper File or InputStream from this u

  • List- Export- Spreadsheet option disabled in ALV Report

    Hi, In one of the ALV Report the option List->Export->Spreadsheet option is disabled. How to enable that option? I am calling the REUSE_ALV_GRID_DISPLAY Function module with the following parameters     CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'       EX

  • Web Sharing goes Haywire

    I've been using Web sharing without any incident on my machine for the last 4 months. I have not installed any new software or updates for at least 1 month, so I cant figure out why Web Sharing just plain does not work anymore. Visiting http://localh

  • Firefox will not connect to internet

    All of a sudden tonight I can no longer connect to the internet thru firefox. Pc is about 2 years old, came with McAfee but I've never activated it. Error says 'Unable to connect' and 'Firefox can't establish a connection to the server anywebsite.com

  • Mysql-connector-java

    Hello with all I have only one question, how to install mysql-connector-java under the archlinux, because I have to seek, is I do not have to find, it is for me to make a test with opencms, I seek a howto more precisely, thank you MM:/