Discussions

EJB design: Why I hate Entity Beans

  1. Why I hate Entity Beans (66 messages)

    I have just read through the patterns section of Floyd's EJB Design Patterns book. I have been using Entity Beans (and Session Beans) for about one year doing a messaging system. I am also involved in producing a component that provides user administration features through JSPs. The JSPs deal with domain objects like person, company, role, address, contact details etc. Rightly or wrongly, I want the JSPs to deal with these domain objects as plain old java objects because it makes them more readable and meaningful. So, here is the problem I have with using EB in this context.

    For every domain object:

     * I require a home interface
     * I require a remote interface
     * I require a implementation class
     * If I am using the Business Interface pattern, I require a business interface
     * I require a standard deployment descriptor
     * I require a app server specific deployment descriptor
     * I require a session bean with methods to get the data my JSPs require
     * I require a DTO
     * I require a DTO factory, or serveral of them to match the methods on my Session Bean.

    If I have 40 domain objects (which is what I have and it ain't a big system), this is a helluva lot of classes and files. Even with XDoclet or the most capable IDE, its still a helluva lot of work.

    Many of the patterns in the book are, in my view, aimed at improving EB performance and compensating for their other deficiencies (like the mixing of remote capabilities and persistence as has been discussed already on this site). So it seems to me we are jumping through hoops to use EB as nothing more than a mechanism to keep SQL out of our code (load from DB using EB, then convert then to DTOs).

    I also want to keep SQL out of my code and have as much transparent persistence as possible, but I don't want to have to do all of the above. In fact, all of the above indicate to me that EB is broken, or at best, badly maimed and that we should be looking for something better.

    When I look at ObjectRelationalBridge or JDO I cannot help but lean towards them. I have plain old java objects and transparent persistence and DTOs all in one. I should still use the Session Facade of course, but this time its purely for layering purposes instead of compensating for the poor performance of my persistence layer.

    I have no idea how ORB or JDO will perform or scale in relation to EB, but its clear my development time is less, my code is clearer and my maintenance effort is lower. Counting the effort required to add or remove an attribute to all of the files listed above depresses me.

    This is a contentious issue. I have serveral colleagues at the company I am working for barking at me that I must use EB because it is proven, scalable (and since they are architects they further clarify that they are scalable horizontally and vertically ;-) ), performant and standard. Well they are also a pain in the butt, and I'd like to see if there is a better way.....?

    Threaded Messages (66)

  2. Why I hate Entity Beans[ Go to top ]

    You know, i'm in the same disposition as you are, but I'm not really working for a company. I have a site that I'd like to build that has around 56 tables. It's a pretty big site where maybe some of it could be put into small xml files or something and maybe then it'll go down to 40-45 but still - that's a ton of work.

    I also have little money, so I don't have $5000 canadian to get rational xde and have all my problems solved. If i did, I wouldn't be using orion or mysql. The thing that burns me the most is that the DD files, the ejbs (the ejb itself and the localhome and local interfaces, the dtos, the dto factories, etc. can *all* be generated through the sql creation logic with maybe a few design decisions specified to make sure it comes out okay. To me, the spec should have emphasized that all this be generated by the app server or something because it's kind of rediculous all the monkey work that is required. I mean, after you have the design on paper, the work is very tedious and it's not rewarding, regardless how scalable, performant, etc. it is :/

    I don't really have an answer to your question other than that I am with you =) JDO sounds like a sensible solution to the problem, but they will never put it into j2ee directly, so that makes it really tedious and just more load of stuff to learn and I dunno if the ROI on the learning and doing is really paying off. It's really too bad.
  3. Why I hate Entity Beans[ Go to top ]

    Middlegen is a free, open sourced tool that reads database metadata and generates Entity Beans OR JDOs that can access the same database. If you generate Entity Beans, you can post process them with XDoclet (which is also open source and free).

    Tools like this minimises the development overhead dramatically. If you can have 90% of your code (including deployment descriptors) generated for you, I don't see the problem why there are so many files involved. A large number of files is not a problem as long as you don't have to write them yourself.

    Those of you who want to try out Middlegen/XDoclet are encouraged to try the CVS versions. Both tools have evolved dramatically since their last releases.

    Aslak
  4. Why I hate Entity Beans[ Go to top ]

    -Just a comment:

    It strikes me how alienated people are to code generators. The tools I mentioned in my previous post aren't the only ones available of course. There are heaps of both commercial and open source tools that virtually remove the problems you are complaining about in this thread: Complexity.

    A car is a complicated piece of machinery. Still, a lot of people use them. Guess why? -Because they don't have to build them themselves! Somebody else does. Only crazy paople would build their own car.

    For more info about this, just read this thread:
    Metadata-based code generator. It has a lot of useful comments and links to other good tools.

    Aslak
  5. Why I hate Entity Beans[ Go to top ]

    Aslak,
    I agree with you. The fact that EJBs are internally complex and are composed of multiple files shouldn't be important.
    It seems to me that people often think about EJB in terms of performance, loosing the focus on another important aspect: speed of development.
    EJB containers have been created factoring out all the most common solutions from existing applications/frameworks/solutions and transforming them into common services.
    They are obviously complex things but developers can be shielded from the container's complexity by any good IDE.
    It's my opinion that EJBs aren't perfect and doesn't fit in the same way for every scenario but they're a good approach at architectural design of complex systems.
    Again, EJBs can be a good solution to reduce developing consts factoring out common solutions and focusing on the real business logic.

    Claudio
  6. Why I hate Entity Beans[ Go to top ]

    The power of EJB is the services that container can provide to developer. Concurrent service, transaction service, a consistent container based framework. It doean't mean your classes/interfaces are simpler than JSP/Servlet.

    We are developing CORBA based system, we have to handle a lot of thread consurrent issues by ourselves, we have to invent our own transaction-like mechanism(because not all ORBs support OTS), we have to develop our own plugin framework, We have to write code to implement our configuration interface...

    If giving me a chance to determine which one I want to use next time, I will vote on EJB/Application Server, we still have pain on EJB, but less than CORBA.
  7. Why I hate Entity Beans[ Go to top ]

    You say that your system is not big but that you have 40 domain objects. I would suggest trying to make the granularity of your components coarser by using one of the patterns posted here on TSS.

    EJB components do carry a development and performance overhead - but in return provide deployment time encapsulation and a number of enterprise level services. Choose a level of granularity that is too fine, however, and this overhead becomes disproportionately high.

    If there is no natural partitioning of your domain objects at any level, then (as you suggest) consider exposing them at the service level via a session bean interface. Whichever technique you adopt, you can use JDO - I am not a great fan of CMP except in trivial systems.

    Colin.
  8. Why I hate Entity Beans[ Go to top ]

    Colin,

    I hear what you are saying about making the EBs coarser, but the 40 object I am talking about constitute the domain model we think is right. If EB cannot persistent the domain model we think is right, we think EB is wrong. That view might be a little fundamentalist (I hope I am not on George Bush's hit list), but it does suggest the existence of something better. JDO seems promising, but is it yet mature and proven. Also I have not yet used it. I'd love to hear some anybody who has.
  9. JDO[ Go to top ]

    Mike,

    I've been using Kodo JDO (www.solarmetric.com) for a couple of months. I find it very easy to use, especially if you let it produce your schema for you, and find that it integrates well with EJBs (I'm using jBoss).

    I don't see any problem with JDO being 'outside J2EE'. With JCA JDO can participate in transactions just as happily as other persistence techniques.

    I haven't yet tested performance/scalability, but there is no fundamaental reason that I can see that would make this worse than entity beans. Kodo has a cache which can span JVMs, which you can use if your application has sole access to your DB. Yes, you are dependent on your (JDO) vendor's cache scheme, but at least this doesn't lock you into an app server vendor, as CMP can.

    I recommend JDO.

    Tom
  10. Why I hate Entity Beans[ Go to top ]

    My group is moving away from EJB for many of the reasons you discussed. Quite simply, for most projects, EJB's are like swatting a fly with a pickup truck. Too much of everything. We _do_ use some EJB's, but there is usually a specific need associated with EJB's that causes us to choose them in an instance (like we need/want container lifecycle management and callbacks, or remote etc).

    JDO looks nice, but none of the implementations seem to be "there" yet, except maybe Castor (which isn't JDO compliant). Object Relational Bridge is really nice, and is in the process of implementing JDO.

    I have just started using Object Bridge for one of my projects, and so far its really nice. It gives me far greater flexibility than EJB, and it's a lot less overhead. The downside to this is that transactions and security are not code independant, but that's not that big a deal. How many people really write one EJB and then use it in different declarative environments (ejb-jar.xml) for security and transactions? We never really need to.

    I've been talking to other J2EE architects and developers and I keep seeing this same little mental cycle among these people. First they start out and say, "Wow, EJB is the greatest thing ever." Then they do some large project(s) and the thinking becomes, "Man, this is a lot of development, maintenance, and overhead." Finally a lot of these people are saying, "Unless you _REALLY_ need it for technical reasons, skip EJB and do something else." Is there another step? Maybe I just haven't gone through the whole cycle...

    Maybe part of my problem is that I haven't worked with EJB 2.0 yet.

    -Newt
  11. Why I hate Entity Beans[ Go to top ]

    Oy...I'm just starting my first really major EJB project at a new company, and somehow I missed that whole "EJBs are the greatest thing ever" and landed right in the other views of "wow that's a lot of work" and "huh maybe this is overkill".
  12. Why I hate Entity Beans[ Go to top ]

    OK, Entity beans aren't that bad, in terms of complexity, compared to what I've found implemented here in my new job!!! The last job I has I was designing a scheduling system that had 20 entity beans in it, spoke XML over HTTP to a graphical client, and had to be generalist in it's nature so users could customise what sort of scheduling applications it was being used in. So, it was fairly complex.

    But, compared to what I've found in my new job, it's nothing. There are three session beans, a whole lot of ugly 'model' classes the by the database access object uses reflection on in order to get the field names, (i.e the model class's fields have to exactly match the database table's), with the table name plus some other things like a single allowable foreign key lookup being stored in a properties file. So much is determined at run-time in the introspection, it's insane. Just to add a piece of functionality that would normally take me 4 hours takes me 4 DAYS because of the amount of time in code inspection. Even to rewrite it (what I'm doing now) to get rid of the most insane parts of the design it's the most hideous thing imaginable. Some 'model' classes model 5 different tables (I discovered this morning after much detailed code inspection). And did I mention that there are over 200 classes to contain 10 domain objects and about 6 real business methods!!!

    My predecessor spent the last six months putting out the major fires and getting rid of as many of the bottlenecks as possible. He had inherited this design off some half-arsed consultants who over-engineered the whole package and obviously never read any GoF patterns book let alone a J2EE one. They employed visual basic programmers to write the thing -- it's a mess! Needless to say the consultancy company is no longer in business.

    Anyway the point I'm trying to make is that if they had at least written a poorly-designed EJB entity system, at least I'd still know how and where to look for things, I want to know about the system, and what to do in order to re-engineer it, and where the likely perf. problems are.

    So please don't complain to me about the complexity of EJB. ;-)

    regs
    scot.
  13. Why I hate Entity Beans[ Go to top ]

    Scott,

    I'm not sure that your example is a particularly good one. All of us have probably been stuck in projects like yours.

    The question at hand isn't whether or not EJB is good compared a really badly designed system like the one you're working with. The question is one of some standard methodology for developing these type of systems. Even with EJB, systems like the one you are referring to can happen, as they can with just about any development convention.

    My question to you is: Have you worked with EJB, JDO, big JDBC hand coded projects, and Object Relational mapping?

    If you _have_ worked with at least a few of these, would you still choose EJB as your standard for development.
    Of course, a requirement like distributed would make the choice obvious. pretend like you're not looking at a model that is that specific.

    To be honest, if you haven't worked with at least a couple of the alternatives, I don't think you're necessarily qualified to make a judgement. That would be like saying "I hate running a mile" even though I can't run a mile. Only once you've done it do you have the mental "choice" to say, "I hate running a mile."

      I've worked with all of them, although less JDO than the others. And I'm beginning to move away from EJB towards JDO/ORM. These tools are easy to use and can provide lots of value just as EJB's can. What's more is that I'm finding that a lot of our peers are beginning to feel the same way.

    -Newt
  14. Why I hate Entity Beans[ Go to top ]

    I haven't worked with a JDO project, however, the others yes. I've done reasonably large scale financial systems using hand-rolled JDBC, for example. I think the current project may have been generated or based on the generated code from some sort of O-R tool, there are a couple of 'automatically generated' comments at the top of a few of the map classes (by what it doesn't say).

    If I had to do anything that had a web based front end, I certainly would consider EJB. Probably, a mix of EJB entity for major objects and session beans fronting JDBC access for dependant objects and large row number read-only queries.

    There are perfectly good EJB tools available in all the major IDEs which make working with EJB system as easy as any O-R mapping tool.

    The thing is, there are two questions to answer: First what's the best architecture for the system? Second, what's the most productive architecture to code to? I am not here to say "EJB is good in all circumstances" or "EJB is best" but on the other hand when I hear "EJB is bad" I can only point out, it's much more hassle dealing with BAD DESIGN IN GENERAL than in any particular architecture in particular. What works is good and works well is better and what works and is easy to maintain is best. I have tended to observe that it all starts with good, clean design in the first instance, and that makes the biggest impact on maintainability of the code.

    regs
    scot.
  15. Why I hate Entity Beans[ Go to top ]

    Fair enough. I didn't say that EJB is bad, I just see a lot of people (myself included) moving away from it. I still like it for doing some jobs, as I said above, but it's no longer my standard convention.

    Well said though, and true enough.

    -Newt
  16. Why I hate Entity Beans[ Go to top ]

    Newt et al,

    You guys should try webobjects, it is alot more advanced than all this EJB stuff. EJB in my opinion is very primitive and has a too many classes to access a single database table. I just started working with EJB and not that it is too complex, but as most of you have rightly pointed out. Too much maintaining to do over a minor change. It surprises me how better technologies don't get noticed.

    So as I pointed out, you might want to consider playing with http://www.webobjects.com and you will see why EJB is an overkill. The only problem with webobjects is that it's marketshare is poor, but if you tried it, you will dump EJB in a heart beat. Give it a shot.

    Chi.
  17. Why I hate Entity Beans[ Go to top ]

    As it is right that WebObjects is a lot smoother in development and much less complex, at deployment time pure J2EE app servers are more powerful (e.g. granularity in deployment is not by instance).

    However, WebObjects has a OR-tool, that is quite decent: EOF ... what I would like to know is, if somebody has ever tried to integrate EOF in EJB?
  18. Why I hate Entity Beans[ Go to top ]

    Yes, it's called GemStone/S.

    Cheers,
    Jeff Panici
  19. Why I hate Entity Beans[ Go to top ]

    I've been working with EJBs for over 3 years now. Needless to say, all the points Mike made has been a pain in the neck for me, too.

    On our last project, we have used IBM's WebSphere Studio Application Developer tool and now I am convinced that the cause of our problems had been incomplete, incompetent tools. Developing EJBs is a cumbersome business without the right tools. There's no denying that EJBs (both in theory and practice) are not straightforward; but a good tool can hide all the complexity, letting you focus on your development.
  20. Why I hate Entity Beans[ Go to top ]

    So now we are faced with the choice between forking out for an IDE that compensates for EBs lackings OR forking out for a commercial JDO implementation. Ain't life grand ;-)
  21. Why I hate Entity Beans[ Go to top ]

    I disagree... proper usage is the key to ... using EB's for every sing domain object is an overkill... some things (which donot require frequent transactional updates) donot qualify as a "value-for-time" EB.. i.e. u'd be wasting time if u implemented it as an EB. EB's when used properly provide good performance and reliability. The systems have lesser critical bugs. but this does not illustrate the fact that Using EB's correctly is no casual deal... u need to plan and architect... and i would suggest not testing this on a primere project... do sand box tests...learn form your mistakes here or on small projects... this is not an article...just a post... so i will not delve into what "using properly" means.. but i'll be happy to delve in an email conversation... if need be... and for "Lot of code files"... all i can say is packages and proper tools... (together's my fav) deal with these very effectively. On my current project we have EJB's numbering close to about 100..120... 6 developers.. some 600 odd screens... but I donot see the developers overwhelmed... a key reason is the effective usage of patterns.

    Cheers
    Adi
    adiand@usa.net
  22. Why I hate Entity Beans[ Go to top ]

    Hey, wait a minute!
    As in many "I hate EJB" forums everybody seems to miss the whole point on EJB (and, of course, say that EJB=Entity EJB)

    The last project I was involved was somehow a tipical WebStore. It has 65 Fine Grained Entity Beans for Domain Object representation, 1 Stateful Session Bean (Shopping Cart) and 1 Stateles Session Beans modeling the only critical bussiness process that needed to be TRANSACTIONAL
    (that it, sending the order to the warehouse). Of course, we used EJB1.1, so we didn't have local iterfaces.
    How much time it took me to develop all those beans?. Make your guesses, but if your're informet you'll guess "less than 4 hours". I used a home-brew code-generator (2 hours of coding). In 1 hours I wrote the definitions of the beans (properties files, 0 java code, less that 10 lines in each) and the code-generator created all the classes, deployment-descriptors and DB scripts I needed. Half and hour customizing some descriptors and Half and hour running the DB script, deploying the beans and testing the stuff.

    No that we put out all the code complexities of EJB, we are left with only 3 complains:
    1.- It doesn't map very well to a relational database (this is called "Object-Relational Impedance Mismatch" in Ed Roman book)
    2.- The Network Roundtrip for RMI calls makes multiple finegrained calls expensive
    3.- BMP sucks

    For 1) one little known trick is that you can define the Datasource your ENTITY BEANS will be using, (on EJB1.1 this was done on a app-server specific basic. I readed that EJB2.0 has a pluggable persistance mechanism. I'll check the spec ASAIC) so you can use CocoBase, toplink or a JDO implementation. You'll need a JDBC driver anyway, but it's worth a shot. (I hear of people using Cocobase with Orion App Server).
    OR, you can use an app server that has a powerfull O/R mapping built-in (like orion)

    For 2), with local interfaces that's solved. And most robust app server detect if the call is a local one and don't use RMI anyway.

    For 3) I agree. Simply don't use BMP. The only reason I can ssee for BMP are complex queries in findBy methods. Use the "JDBC for reading" pattern and voila, no more BMP.

    Now, EJB technology is not a "silver bullet". It ease you the burden of resource pooling, explicit transaction demarcation, persistance and multi-threading. Used properly you can engineer a system in less time. Missused will only give you FUD and frustration.

    And, yes, I have used JDBC, EJB, O/R mapping tools, CORBA and early version of JDO.

    This was quite a rant... But I hate to see EJB beaten to death without mercy...

    PD: I didn't read all of the post before writing this one.
    Scot mcphee already said some stuff that are very true.
  23. Why I hate Entity Beans[ Go to top ]

    Having use all of the above (except JDO, which, like most, I've only read about since its just become standard), I can say, absolutely, without a doubt...It all depends on the problem you're trying to solve ;)

    If you have a non-transactional, read-mostly system, its *usually* overkill to use Entity EJBs. Session EJBs are almost always a good idea if your system might be used by different clients. I don't use stateful session beans for anything, your mileage may vary. Generally, though this is because Web apps work pretty well with session state or by storing state in a database.

    If you have a Web-only, will never be anything else kind of system, I like using plain old Java class "business delegate" interfaces along with Data Access Objects that contain the SQL and JDBC. You can use these with app server DataSources to get pooling, etc.

    ORM tools are pretty good if you *need* everything to be an object. I find that for most query applications, this isn't the case, and is in fact often harmful. Its OK to return result sets (or RowSets, Tables, etc.) from a query if you have fairly dynamic reporting or display needs (custom user sorting, searching, etc.).

    Summary: Start with straight layering (Business Delegate/Facade and DAOs), then if needed, insert session beans (behind the delegate), and finally entity beans (in the session beans). By layering, you're never coded into a corner.

    As mentioned earlier, you can always just do code generation ;) There are at least a half dozen products that can take a DB schema and crank out all the layers for you. Use them.


  24. Why I hate Entity Beans[ Go to top ]


    >>Maybe part of my problem is that I haven't worked with EJB 2.0 yet.

    I think this is a primary part of the problem. CMP2.0 is not just an optimisation - its a quite large change. You definitely DONT want to be pissing about with CMP1.1 any more. Most complaints (CMP is slow, for example) comes down to people who have used CMP1.1 and dont recognise what CMP2 means.

    I will agree, however, that there is a large barrier to entry when it comes to using EJB - entity beans in particular. However, there are many "barriers" in EJB that are there for good reasons.

    Barrier 1: Cost. Most decent containers are not cheap. (I havent checked JBoss in the last 3 months to see how their container has improved). It would obviously be better without this barrier ;-)

    Barrier 2: Complexity. There are quite a few classes and deployment descriptors to write.


    But lets look at the counter-arguments
    Cost: Its true that the high-end containers are expensive. However, the nice part of using a standard approach is that you can migrate up as you can afford/require it - its standard.

    Complexity: Too many classes. This the most common one I hear.
    Interface, Home, Remote... :
    The truth is that you always want to code to an interface when it comes to your domain model. Your domain model will be with you for a long time - and lots of things will depend on it. You need to be able to change implementation - so a Interface and Factory (remote/local and home) are just good practice if you expect your system to have any lifetime.
    DTO's etc:
    Well, you need some kind of object for data transfer - but its important to remember that DTO's are use-case oriented. You need to decouple the DTO representation from the domain model (otherwise all you client systems become inter-dependant, via the domain model)

    JDO significantly lowers the barrier to entry - when it comes to O-R persistance. However, keep in mind that for most serious projects, these complexities will exist no matter whether it is JDO or Entity Beans. JDO just gives you more rope to hang yourself in my mind (not enforcing the use of interfaces). JDO is without doubt a good competitor to JDBC (you get a graph of objects rather than a flat ResultSet) - but it is the component model of EJB that is interesting.

    Ultimately, keep in mind that a standards based system (be it Entity Beans or JDO) will be many times easier to maintain than some home-brewed or obscure persistance "framework". At the very least, if you place a job ad for "EJB experience" or "JDO experience" in 2 yrs time, you will get some people who know it (even in 4-5 years time). If it is home-brewed, you can be sure that you wont have anyone who knows the "framework" after just 2 years - and then it will be unmaintainable (no matter what the metrics are on the number of classes).

    Even in 10 years, you will still find books for EJB and JDO...

    There is always room for improvement - but no strikingly "better way" has shown itself recently, in my mind.

    Cheers,
    Nick
  25. Why I hate Entity Beans[ Go to top ]


    It really scares me when people say that EJB 2.0 is a vast improvement on 1.1. I've used only 2.0, and it is a hard slog to get anything done.

    Take a few examples:

    (a.) Relationships.
    These need to be defined in:
    1. ejb-jar.xml
    2. server specific xml
    3. bean
    4. local/remote interface
    5. home interface (create methods)
    6. Value Objects maybe too

    So change a relationship on your DB, and you've got some work to do.

    (b.) Finders
    1. ejb-jar.xml
    2. home interface

    Every time anybody wants to add a finder, they need access to the ejb-jar.xml file. What does a finder have to do with deployment?


    (c.) Now let's create a new entity bean

    Object home = ctx.loogup("MyBean");
    MyBeanHome myBeanHome;
    try {
      myBeanHome = (MyBeanHome)PortableRemoteObject.narrow(home, MyBeanHome.class);
    }
    catch (Exception ex){
      // Can't get home
    }
    MyBean myBean;
    try {
      myBeanHome.create("Arguments");
    }
    catch (CreateException ex){
      // Can't create bean
    }

    That's a lot of code to do very little huh?


    I really wonder if the benifits of EJB are worth it.

    Daniel.
  26. Why I hate Entity Beans[ Go to top ]



    >>I really wonder if the benifits of EJB are worth it.
    Compared to..?

  27. Why I hate Entity Beans[ Go to top ]

    Daniel,

    First remember, as it has pointed out lots of times, that EJB are not ONLY entity beans, and that entity beans are not OLNY a way to persist. They represent your Domain Objects, is just that these objects know how to persist themselves, and it just happen that they support transactions, can be pooled for resource efficiency, etc,etc.

    Let's examine all your examples:
    >Relationships.

    >These need to be defined in:
    >1. ejb-jar.xml
    >2. server specific xml
    >3. bean
    >4. local/remote interface
    >5. home interface (create methods)
    >6. Value Objects maybe too
    >So change a relationship on your DB, and you've got some >work to do.

    Ok. It look like you're mixing things. If you use BMP Entity Beans you need to define relationships on the bean implementation. If you use CMP, you declare the relationships in the ejb-jar.xml. SO, if you change a relationship in your DB, you need to modify only 1 file.(the amount of work needed if you use BMP is another matter)
    (Free advertisement: Check the Ed Roman book, available free for download in the resource section. Page 325)

    >(b.) Finders
    >1. ejb-jar.xml
    >2. home interface
    >Every time anybody wants to add a finder, they need access
    >to the ejb-jar.xml file. What does a finder have to do
    >with deployment?
    You declare the signature of the method in the factory (where it belongs). Now, instead of implementing it in the bean you declare it in the ejb-jar.xml, because it's easier to debug and modify. I prefer to modify an xml file and redeploy rather that recompile a class and redeploy, but that's just me.

    >c.) Now let's create a new entity bean
    >
    >
    >Object home = ctx.loogup("MyBean");
    >
    >MyBeanHome myBeanHome;
    >
    >try {
    > myBeanHome = (MyBeanHome)PortableRemoteObject.narrow
    >(home, MyBeanHome.class);
    >}
    >catch (Exception ex){
    > // Can't get home
    >}
    >MyBean myBean;
    >try {
    > myBeanHome.create("Arguments");
    >}
    >catch (CreateException ex){
    > // Can't create bean
    >}
    >That's a lot of code to do very little huh?

    Ok, let's suppose you want to use JDBC:

    try {
         Class.forName(MyJDBCDriver);
    } catch (ClassNotFoundException e) {
    //there is no MyJDBCDriver
    }
    Connection con;

    try {
         DiverManager.getConnection(myURL,myLogin,myPassword);
    } catch (SQLException e) {
    // Couldn't connect
    }
    Statement sta;
    try {
    try {
    con.createStatement();
    } catch(SQLException e) {
    // can't create statement
    con.close();// beware of leaking connections!!!
    return;
    }

    try {
    sta.executeUpdate("INSERT INTO yourtable(<list-of-field-name>) VALUES(<list-of-field-values>)");
    } catch(SQLException e) {
    con.close(); // beware of leaking connections!!!
    //can't create the stuff
    return;
    }
    try {
    sta.close();
    } catch (SQLException e) {
    //cannot close statement;
    }
    con.close();
    } catch (SQLException e) {
    // Cannot close connection
    }

    That's WAY a lot more code. Of course, you can optimize it encapsulating the connection and statement creation, and ALSO you can encapsulate the Home adquisition or the create method.

    After all this BIG FLAME, the message is: If you want to criticize a tecnology, be sure of what you're saying or prepare to be flamed. If you don't like the way something is done, think first what is the way you would do it and balance the pro's and con's.
  28. Why I hate Entity Beans[ Go to top ]


    Rafael,

    Well I can see that you have read the books on EJB... I get the feeling though that you havn't quite gotter around to actually using Entity beans yourself.

    > First remember, as it has pointed out lots of times, that
    > EJB are not ONLY entity beans, and that entity beans are > not....

    Read the title of the thread. All my examples were of Entity beans, except one which is general to all EJBs.

    a) Relationships

    > Ok. It look like you're mixing things. If you use BMP
    > Entity Beans you need to define relationships on the bean
    > implementation. If you use CMP, you declare the
    > relationships in the ejb-jar.xml. SO, if you change a
    > relationship in your DB, you need to modify only 1 file.
    > (the amount of work needed if you use BMP is another
    > matter)

    Um (stunned silence), I'll make it a bit clearer for you. I want to add a new CMP (yes that's CMP) bi-directional relationship, using existing keys in the DB. (ie the keys already exist in the DB and in the BEAN, but the relationship isn't defined yet).

    Lets see what I have to do:

    1. ejb-jar.xml
       - Add relationship tags
       - remove CMP fields

    2. server specific xml
       - Add the relationship tags
       - remove CMP fields
       - (* Note I've only used Weblogic, so this may differ)

    3. bean
       - Add Relationship getters & setters in both beans.
       - Remove the CMP field getters & setters.
       - Remove the CMP fields from create.

    4. local/remote interface
       - Remove CMP field getters & setters

    5. home interface (create methods)
       - Remove CMP fields from create

    6. Value Objects
       - Remove CMP fields from both VOs

    So that's 1 ejb-jar.xml + 1 weblogic-jar.xml + 2 beans + 2 home interfaces + 2 local/remote interfaces + 2 Value Objects = 10 files to modify. Feel free to recalculate that for me.

    b) Finders:
    I won't bother arguing much here, this is a personal thing. I just can't see what a finder has to do with deployment... But that's just me.

    c)
    > That's WAY a lot more code. Of course, you can optimize
    > it encapsulating the connection and statement creation,
    > and ALSO you can encapsulate the Home adquisition or the
    > create method.

    Very good. JDBC requires more coding then CMP entity beans. (Pretty scary if it didn't). I didn't write a comparison - I just said that Entity beans are verbose. I don't know what is better. I just know that Entity Beans are not what I'm looking for.

    > After all this BIG FLAME, the message is: If you want to
    > criticize a tecnology, be sure of what you're saying or
    > prepare to be flamed. If you don't like the way something
    > is done, think first what is the way you would do it and
    > balance the pro's and con's.

    I agree with everything you say in this paragraph (see, we can be friends). Maybe apply it to your own writing :-)

    Cheers,

    Daniel.
  29. Why I hate Entity Beans[ Go to top ]

    Daniel,

    First of all, I want to apologize for the high tone in my "FLAME POST", but I'm getting tired of people that say "EJB sucks" just because they screw it the first time and instead of looking for the whys they just blame EJB ( I had to remake the whole design 3 times until I started to get a grip on the concepts). You're of the second category, those who emit informed opinions. Now, to the post :)

    a) Relationships: oops, my bad. I din't saw the code-cleaning needed. So, I will eat the flames.

    b)Finders: Yes, this is a debate as productive as the one on "where the { should be: end of line or new line?"

    c) Yep, EJB are verbose, but it's not EJB fault, is Java fault. All those try/catch are needed for recovering from unexpected situation, and Java enforces it. We both exagerated the examples a little, we could surround the whole code with a single try and multiple catch (after all, all the instruction can be considered a functional block). Much more readable. AFAIK, JDO is at least as verbose as EJB, and JDBC is WAY more verbose.

    I'm curious when you say that "I just know that Entity Beans are not what I'm looking for". Well, I'm curious is about what you're looking for, 'cause perhaps a framework over JDBC/EJB/JDO is the answer. Can you email me (soronthar at flashmail dot com) for further discussion?

    And yes, we can be friends (even if you hate EJB ;))

    Rafael
  30. Why I hate Entity Beans[ Go to top ]



    Why do you feel you need to remove the CMP fields?

  31. Why I hate Entity Beans[ Go to top ]

    Rafael,

    Maybe I don't get it. People keeping saying this, and I can't see how it can be true.

    "Entity beans represent your Domain Objects, is just that these objects... ...can be pooled for resource efficiency"

    What makes you think pooling of Entity beans gives noticeable efficiency gains? Hey, I know, object creation does cost. But given an object with 20 fields (which are Strings, Dates, etc), that means I need to load (and create!) 20 Objects from the database when I re-use an Entity bean instance. That costs so vastly much more than the creation cost of a single object that the cost of creating the single object is insignificant. So my pooling of the bean object itself gains me (practically) nothing.

    Have I missed something?

    (Now, EJB containers doing resource pooling of database connections, JMS Sessions, etc *is* an advantage - but that's a different matter).

    Sean
  32. Why I hate Entity Beans[ Go to top ]

    What makes you think pooling of Entity beans gives

    >noticeable efficiency gains? Hey, I know, object creation
    >does cost. But given an object with 20 fields (which are
    >Strings, Dates, etc), that means I need to load (and >create!) 20 Objects from the database when I re-use an
    >Entity bean instance. That costs so vastly much more than
    >the creation cost of a single object that the cost of
    >creating the single object is insignificant. So my pooling
    >of the bean object itself gains me (practically) nothing

    If your point is that creating n+1 objects has the same cost than creating n when n is a large, point granted. If not, I missed your point entirely.

    There are two things to consider: Garbage Collection and Heap Space. If you have a request to 1000 entity "objects" with 20 fields stored in a collection, you will have 20000 objects created that will not be collected by the GC until you finish with your collection and the collection is collected itself. Also the time of collecting them is high (depending on the GC strategy your JVM is using)If you use a pool, you will have only (objects-in-pool * 21) objects created, and the instance variables of each instance will be collected as soon as you finish using that instance (well, not exactly but a good aprox). Of course, you have the ejbStore, ejbLoad, ejbPasivate and ejbActivate call and execution overhead, but they can be implementeted in a way that it is small compared to the time of GC or to the improvement in the Heap use.
  33. Why I hate Entity Beans[ Go to top ]

    Hi,

    Our main point of disagreement is this:

    "Of course, you have the ejbStore, ejbLoad, ejbPasivate and ejbActivate call and execution overhead, but they can be implementeted in a way that it is small compared to the time of GC or to the improvement in the Heap use. "

    That's just not my experience when I profile J2EE apps. My belief is that the cost of saving and loading to/from a database is huge compared to the cost of keeping a few extra objects in memory. That's why in-memory caching of objects is generally considered a good thing.

    Sean
  34. Why I hate Entity Beans[ Go to top ]

    Sean,

    I dind't make my point clear. Let me clarify the statement

    "Of course, you have the ejbStore, ejbLoad, ejbPasivate and ejbActivate call and execution overhead, but they can be implementeted in a way that it is small compared to the time of GC or to the improvement in the Heap use"

    When I say "call and execution overhead" I mean the cost to invoke the method (prepare the call and execute the call by the JVM), not the execution of the method per se.

    I totally agree with you that the execution of those calls can be very expensive, but if you implement them so they don't touch the database unless needed (for example, using a "dirty flag" in the ejbStore method to decide if you need to persist or not) then the cost to invoke them is neligible compared to "the time to GC or to the improvement in the Heap use".

    Besides that, I cannot agree more with your two latest posts.

    Rafael
  35. Why I hate Entity Beans[ Go to top ]

    The Oracle Business Components for Java J2EE framework provides a robust and proven solution to some of the original concerns raised by the original poster of this thread. Over time we're adding support for entity beans for developers who are convinced that's the way they want to go, but most of our users do benchmarks and choose the simpler choice of lightweight entity classes today.

    We let you deploy an EJB Session Bean facade with these lightweight entity classes inside it, or you can also use the Session Facade as a simple java class, too.

    Hundreds of web application developers in our Oracle Applications division use our framework.

    Simplifying J2EE and EJB Development with BC4J
  36. Why I hate Entity Beans[ Go to top ]



    ... And you can also use Oracle Business Components on Sybase, Ingres, DB2, SQL Server.......

    Stick to standards, is my advice - be it JDO or Entity Beans.

  37. Why I hate Entity Beans[ Go to top ]

    Nick,

    I don't see the rationale in fronting your domain model with interfaces since there will be a one to one mapping between the interface and the implementation. When I speak about domain objects I mean dumb nouns with getters and setters. If a interface is required to front domain classes, why are they not required to front DTOs?

    As I see it, there should be very little difference between DTOs and domain objects. Ideally they should be the same. I can see that some use cases would require custom DTOs. But to say that presentation layer components need to be insulated from domain objects is debatable in my view (they are not insulated from DTOs).

    If you are writing a presentation layer that sells books, the presentation layer is going to have to deal with books. De-typing books into a hashmap to avoid this coupling has as many disadvantages as advantages.

    Another fallout of having the domain model and DTOs differ is the introduction of DTOFactories (and the DTOs themselves). So it is true that EB will require more classes, even if an IDE generates all the EBs for you.

    I have finally finished Floyds EJB design pattern book and he has almost an entire chapter devoted to JDO. Take a look at it and see how clean the code is. DTO and EB become one, DTO Factories disappear, business, remote and home interfaces all disappear. His view is that making EBs as components is what reduced their usefulness and that seems right to me. All I want is persistent DTOs.
  38. Why I hate Entity Beans[ Go to top ]


    >>All I want is persistent DTOs.

    In most non-trivial cases, your persistant data model can never be the same as your DTO data model (we will ignore custom DTO's (I am using Floyds terminology here))

    If they are the same, and your persistant data model encapsulates (persists) complex relationships between objects, then when you pass your persistant domain object as a DTO, the serialization will end up dragging over your whole database to the client. OR, you will have to make a break somewhere. Where you break these links/relationships will depend on your particular use-case. Given that you also dont want DTO's with null fields (where you have to do lots of checking before you access a field), then you have to have your DTO's different from your persistant data model, no?

    >>If a interface is required to front domain classes, why
    >>are they not required to front DTOs

    They can if you want. However, usually, DTO's are not re-used as much as your domain objects as they are use-case oriented.

    >>De-typing books into a hashmap to
    I agree. I would never advocate this. (Did I imply this?)

    I dont dispute the apparent simplicity of JDO - but I believe that some of the perceived "overhead" of CMP is actually good for you.
    It all depends on what your system is, what business it is in and how long you expect it to last for.

    Cheers,
    Nick
  39. Why I hate Entity Beans[ Go to top ]

    After reading all the comments on Why EJBs(or rather CMPs) are useless, may be we can take a vote on which of the following did all the developers use so far:-

    1. SesionBean-EntityBean-Database
    2. SessionBean - JDO Impl - Database
    3. SessionBean - JDBC Utility class - Database
    4. SessionBean - BMP - Database
    5. Servlet - JDBC Utility class - Database[no EJB :oP]

    I think we all get the picture, Session Bean is what people never crib about and I think it has it's advantages beyond any other technology. As regards to Entity Beans I think CMP2.0 has though given a lot of flexibility complicated the design of a Entity Bean layer design of my RDBMS. That's where JDO scored it's victory over EB.

    As far as my vote anyday goes to No.2


  40. Why I hate Entity Beans[ Go to top ]

    1. SesionBean-EntityBean-Database

    > 2. SessionBean - JDO Impl - Database
    > 3. SessionBean - JDBC Utility class - Database
    > 4. SessionBean - BMP - Database
    > 5. Servlet - JDBC Utility class - Database[no EJB :oP]

    I have done Systems in 1, 3, & 5. System 1 was the most complex. Actually it went Browser based client application (non-java) -> XML -> Servlet -> DTO -> SB -> EB -> DB.

    I only used 3 & 5 for much smaller systems.

    For the system 1 I also used (for a specialised client)

    Java client -> DTO -> SB -> EB -> DB.

    regs
    scot.
  41. Why I hate Entity Beans[ Go to top ]

    Nick,

    I guess we will just have to agree to differ on whether DTOs and domain objects should be one and the same.

    >If they are the same, and your persistant data model
    >encapsulates (persists) complex relationships between
    >objects, then when you pass your persistant domain object
    >as a DTO, the serialization will end up dragging over
    >your whole database to the client.

    I have not coded this, but from what I can see about JDO, you can surf the object graph as you please, detach it from the transaction (makeTransient()) and return it from a session bean without pulling the db with you.

    Additionally, ObjectRelationalBridge and JDO implementations allow you to do lazy materialization, which will load the data for a referenced object only once you navigate the reference. This works only in the context of a txn of course.


    >>De-typing books into a hashmap to
    >I agree. I would never advocate this. (Did I imply this?)

    No, you didn't imply this, but it is a pattern in the book that helps reduce coupling between the presentation layer and the domain model.

    Cheers,
    Mike.
  42. Why I hate Entity Beans[ Go to top ]

    I read this article about BC4J

    http://otn.oracle.com/products/jdev/htdocs/j2ee_bc4j.html

    and I'm wondering if this made much better sense than the current way of building EJB applications.

    Any opinions?

  43. Why I hate Entity Beans[ Go to top ]


    >>I have not coded this, but from what I can see about JDO,
    >>you can surf the object graph as you please, detach it from
    >>the transaction (makeTransient()) and return it from a
    >>session bean without pulling the db with you.

    Not quite true. Detaching it from the transaction doesnt break the object references that the Java serialisation engine will follow. For example, if you have a persisted linked list, trying to return just the head of the LL will pull the whole LL over the network. The only way to break it is to make a copy - and set some references to null - OR mark some fields as "transient". Unfortunately, marking it transient will also direct the JDO engine not to persist it...
    Therefore, the only option is to clone and set fields to null. This means that on the client, you now dont ever quite know what references you can follow in your "domain" DTO. In order to know, you have to dig around the DTO builder... check if (ref!=null){..} and hope for the best(bad).

    >>Additionally, ObjectRelationalBridge and JDO
    >>implementations allow you to do lazy materialization, which
    >>will load the data for a referenced object only once you
    >>navigate the reference. This works only in the context of a
    >>txn of course.
    I am not sure that lazy loading (a database "serialisation" optimisation) has any relationship to serialization in general. I dont think that doing a read outside of a transaction will change anything. (unless I am completely mistaken). If the reference exists, the serialization engine will follow it (unless its marked transient) (or unless you do your own serialization - ... but forget about that)

    I have a growing dislike for the term DataTransferObject (DTO). I think I prefer calling them a ViewObject. Because that is what they are - a "view" onto the domain.
    My experience has been that your ViewObjects (DTO's) are naturally and necessarily different from your domain. (though, I will admit I didnt realise this straight away)

    -Nick

  44. Why I hate Entity Beans[ Go to top ]

    Nick,

    >For example, if you have a persisted linked list, trying to return
    >just the head of the LL will pull the whole LL over the network.
    >Therefore, the only option is to clone and set fields to null.

    Yes, I see your point on this. But cloning/copying is required regardless of whether you use EB or JDO. Its just that in the case of JDO you use the clone() method, instead of a DTOFactory in the EB case. Setting nulls is certainly bothersome. Would it be useful if the following feature was supported in JDO 2.0:

     * Surf as you please across an object graph in your session bean.
     * Make a call to "makeTransientRecursive()", that will cut out the subset of the graph you have surfed and make that subset available as an independent object graph.

    >This means that on the client, you now dont ever quite know what
    >references you can follow in your "domain" DTO. In order to know,
    >you have to dig around the DTO builder... check if (ref!=null){..}
    >and hope for the best(bad).

    Again, is this not also true in the EB case? The DTO models use (which were prompted by others I see) are object models in their own right and only subsets of them are populated to meet the requirements of the current usecase. You can still surf into a null reference.

    >I am not sure that lazy loading (a database "serialisation" optimisation)
    >has any relationship to serialization in general.

    It doesn't. I figured it could enable a nice mechanism to mark the boundary of a subset of a persistent object graph that could then be detached from the persistent graph and serialized back through a bean interface. We should chat with the JDO guys about this.

    >My experience has been that your ViewObjects (DTO's) are naturally
    >and necessarily different from your domain. (though, I will admit
    >I didnt realise this straight away)

    I'm not trying to be a smart arse here, but if you didn't realise it straight away, how can it be natural or necessary?

    I have been giving a lot of thought to what you say though, and I am coming around somewhat to the view (and getting into this runs the risk of moving away from the title of the thread)

    Providing a layer of ViewObjects that are different to Domain Objects acts as a data contract between the service layer and the layers that depend on it. Not adding this contract means my front end layers are directly dependent on my domain objects (and maybe even my database schema). Now that brings the argument down to whether domain objects are different animals to view objects - in content I mean. If we can go through the pros and cons step by step.

    Assume I have a very simple domain object, a book. It has a title, number of pages and an author name.

    If I want to:

     * Add an attribute, say ISBN. I can add it to the domain class. If I use a ViewObject, I will also add it to that (because presumably I am using it so that front end layers can use it - or is this the presumption you are questioning?). So ViewObject and Domain Object are still the same.
     * Same applies to removing and attribute.
     * Changing an attribute type or name does show an advantage in separating View and Domain objects, as I can just change the mapping code and leave intact everything above the service , which uses the ViewObjects.
     * The real power comes if I want to refactor the domain object into two classes - say Book and Author. Then I can just change the mapping code and again keep those layers above the service layer intact.
     * The inverse also applies, if I want to change an attribute in or refactor a view object, I can do it without affecting the domain objects.

    Does this tie in with what you are talking about? In general, when are View Objects different to Domain Objects?

    The conflict in my mind is that the introduction of ViewObjects seems to break MVC. What is the model when I have domain objects and view objects? Altervatively, are the ViewObjects part of the M, the V or the C?

    After an OO analysis of a domain, I have nouns (the domain objects) and verbs (the actions to be performed on the nouns). The nouns constitute the model, the verbs constitute the controller and work on the nouns, and the views constitute the application interface and also work on the nouns. It is the last clause of this sentence that is causing me problems when it comes to fitting ViewObjects into the picture.

    What do you think?

    Cheers,
    Mike.
  45. Why I hate Entity Beans[ Go to top ]

    A quick PS to this. I can see that the objects in my persistence layer might be different to those exposed by my service layer if I am inheriting a mucky legacy datamodel. Then I see ViewObjects being different to Domain Objects, because the domain objects are already botched.

    But, in the absence of this circumstance, the question still remains: when and why would my carefully designed domain model not meet the needs of my presentation layer?
  46. Why I hate Entity Beans[ Go to top ]

    "when and why would my carefully designed domain model not meet the needs of my presentation layer? "

    One word: "joins".

    Domain models for many of us tend to look suspiciously like relational models. This means that we model individual objects as tables so that we can administer them.

    Later, when you want to do more advanced navigation/reporting/displaying, you tend to be at the mercy of the end user/customer's presentation needs, which often require "rows" of information from several related "tables" or "objects".

    So what we're really talking about is "query" ViewObjects for the most part.

    At this point, you start wondering why you modeled everything as objects, since you need a custom object for each new customer query of the same 4 or 5 tables (or you can make one big fat mega-object that might or might not have its fields populated). How is this easier or better?

    Answer: It isn't. At some point, the benefits of a strongly typed object model for query results starts to break down, and you decide to use a "RowSet" or equivalent technique. You'll see evidence of this as "AttributeAccess pattern", "JDBC for querying", etc., mentioned elsewhere.

    The problem is that the relational model (and SQL) was PURPOSE-BUILT to handle unexpected query situations across different applications without writing custom code (or creating new "objects"). Once you start hard-coding object model on top of this, you're stuck. The best we can do in the object world is to use EJBQL (or OQL, etc), and some sort of Map to hold result attributes.

    I believe that domain objects make sense for transactional (CRUD) operations. For queries (other than the simple, get a collection of Object X), you're probably better off with a generic Map interface like:

    class ResultRow {
       public Object get( String attribute) { ...}
       public void set( String attribute, Object value) {...}
    }



  47. Why I hate Entity Beans[ Go to top ]



    >>But cloning/copying is required regardless of whether you
    >>use EB or JDO

    Thats my point. Creating DTO's is a constant - regardless of EB or JDO (or direct JDBC). However, creating DTO's was complained about as being a "complexity" unique to Entity Beans in your original post.

    >>The DTO models use are object models in their own right and
    >>only subsets of them are populated to meet the requirements
    >>of the current usecase. You can still surf into a null reference

    This is only in the case of bad design, I feel. You should never have a design where this is possible.

    >>I'm not trying to be a smart arse here, but if you didn't
    >>realise it straight away, how can it be natural or
    >>necessary?

    No offense taken ;-)
    Its easy to explain: I didnt fully understand the problem in the beginning. Once I understood, it appeared obvious (its usually the case with hindsight ;-)

    >>Does this tie in with what you are talking about? In
    >>general, when are View Objects different to Domain Objects?

    In general, in your example, you hit all the relevant nails on the head.
    Sometimes your View object will match your domain object - but keep in mind that this is coincidental and transient.
    If you want to display a list of (book title + Author), then your View Object will have the relevent information (Tile + Author). If your domain object happens to have the same representation, then fine. However, as you point out, you are free to refactor your domain model, and create seperate Book and Author objects. Likewise, you are free to refactor your View Object to contain price as well...

    >>The conflict in my mind is that the introduction of
    >>ViewObjects seems to break MVC. What is the model when I
    >>have domain objects and view objects

    In so far as MVC is concerned, this is a layered MVC.
    You can consider the View objects as being the View to the domain (the controller is your business logic). However, your application will see the View objects as the Model (the controller is the presentation logic in this case).

    >>when and why would my carefully designed domain model not
    >>meet the needs of my presentation layer?

    You can safely assume that no matter how much care and design you put into your domain model, it will not meet all the needs of your presentation layer. This is a given. The needs of your presentation layer will be guaranteed to change.
    You should assume that the "mucky legacy datamodel" you refer to in your PS may be your own after 2 months ;-) (despite your best efforts and abilities)

  48. Why I hate Entity Beans[ Go to top ]

    I don't know if this is any help but...

    I don't necessarily agree with most of the issues that have been brought up in the thread, but I did start looking for an alternative when I discovered issues more to do with application servers, etc.

    I came up with a pattern (based on an article I read in DDJ over a year ago, but with much improvement on my part IMHO) that solves most of the EB headaches. It involves a single Generic BMP Bean (which implements the AttributeAccess pattern and manages DB activities), a Generic BMP Bean Primary Key (which manages the details specific to the bean instance, the main workhorse of the pattern), the Home and Remote Interfaces, and Sub Classes of the Generic BMP Bean Primary Key class for every domain object I require.

    The current system I am working on (A complex GIS system containing many enormous tables) contains but one EB, and many Primary Keys, like the one below:

    <pre>
    public class SpecificBeanPK extends GenericBMPBeanPK
    {
    private static final String TABLE_NAME = "TABLE_NAME";

    private static final String[] FIELD_NAMES = {
    "FIRST_FIELD",
    "SECOND_FIELD",
    "THIRD_FIELD",
    "FOURTH_FIELD"
    };

    // denotes that the key contains a
            // single / non-composite key field, and
            // that it's name is "FIRST_FIELD"
            private static final int PK_FIELD_COUNT = 1;

            public SpecificBeanPK(Object[] id)
    {
    super(TABLE_NAME, FIELD_NAMES, PK_FIELD_COUNT, id);
            }

            public SpecificBeanPK()
    {
    super(TABLE_NAME, FIELD_NAMES, PK_FIELD_COUNT);
            }
    } // Yes, That's it!
    </pre>

    I can now have multiple views of the same table (two different bean instances looking at different fields of the same table). The deployment descriptor has the Generic BMP Bean entered multiple times (each with different method transaction attributes, etc.) and each with it's own JNDI name.

    Once you don't mind dealing with AttributeAccess methods and HashMaps (and why would you?) it works like a dream. Of course the 'session facade' is maintained.

    Early reports are that it is quick as bejaysus!. Very quick indeed!

    For the next version I think I will extend it for complex beans involving joins across tables.

    J.K.

  49. Why I hate Entity Beans[ Go to top ]

    Another company out there had a similar idea (i.e. Macadamian Syndeo), its a very curious idea. Generic entity bean seems to be a very appealing idea. Oracle's BC4J has an idea that looks like a cross between the standard and a completely generic bean.

    My take is that the standard EJB approach is fundamentally flawed. Many J2EE design patterns seems to be needed as duct tape. Now there's this proposal to use JDO, this has potential to give back to the programmer things like polymorphism, unfortunately the whole transaction model of JDO is just plain wacky and the weak support for relational databases is just plain unrealistic. So, just maybe Macadamian or Oracle may be on a track that does make sense.

    If we looked at the historical motivations for EJB, we can see that people were evolving the Transaction Monitor idea, that is, of managed and pooled resources, particularly database connections. Somewhere a long the journey, someone threw the idea of Business Objects into the mix. It may be because back then, there was this IBM project called San Francisco that has similarties w/ the EJB idea. Well San Francisco had grand ambitions, unfortunately it was a complete dog and failed miserably in the marketplace. Today we have this J2EE spec that has a solid foundation on TM technology, unfortunately people mistakenly think it provides a means towards the idea of Business Objects (see Oliver Sims for reference). The word "beans" in EJB is what throws people off.

    EJB is extremely weak when it comes to this "beans" idea, in fact there isn't much of a relationship between an EJB and a Java Bean. Until the 2.0 spec there wasn't even a descent way to "link" 2 Entity beans together. The model doesn't even support inheritance or polymorphism. I can't do a query like, give me all vehicles, and get a collection of cars, trucks, planes etc. Any hope of doing something really complex using the standard proposal is a losing battle.

    Clearly, one has to build his domain model like he would do it in Java. Then build Entity Bean Facades to gain the transaction monitoring capabilities of EJB. Thinking that EJB=Business Objects is one way to shoot yourself in the foot. Now I don't know if there's an alternative out there, but Oracle and Macadamian may have in fact something promising.





  50. Why I hate Entity Beans[ Go to top ]

    Carlos,

    > unfortunately the whole transaction model of JDO is just plain wacky and the weak support for relational databases is just plain unrealistic

    Please explain:

     * What is wrong with the JDO transaction model
     * Given that JDO cares not whether you are dealing with an RDB, ODB or flatfile (which is what I assume you mean by saying support for RDB is weak), why is this a negative?

    Cheers,
    Mike.
  51. Why I hate Entity Beans[ Go to top ]

    Mike,

    * I think the declarative transactions of EJB makes more sense, if I can get that while still using JDO then it'll be good. Specifically, regarding JDO, say I've got this object that a grab from a db within a transaction, then I commit that transaction, can I still have access to that object after, and then reuse it in another transaction?

    * I've got a client that displays a table view coming from the server. The table view consists of some fields coming from 2 different objects, the view may contain thousands of entries, now I don't know if you can join 2 classes in JDO or get a subset of the fields of that joined class, I'm assuming you can't. So in JDO its transparent, unfortunately you'll need to grab all fields of both objects to be able to display the table, big performance hit. The whole idea of 100% transparent persistence is completely dubious, in fact Sun in the early days of Java was working on a project for orthogonal persistent java. What happened to it? Simply didn't work out too well. It's a nice concept, unfortunately a pure OO model doens't cut the mustard.
  52. Why I hate Entity Beans[ Go to top ]

    Carlos,

    >say I've got this object that a grab from a db within a
    >transaction, then I commit that transaction, can I still
    >have access to that object after,

    Yes.

    >and then reuse it in another transaction?

    Yes

    >unfortunately you'll need to grab all fields of both
    >objects to be able to display the table, big performance
    >hit.

    (I'm not sure if I understand you, but...) In JDO you still have to specify what db columns are mapped into your object, so its entirely possible to have an object mapped to a subset of a table or view. Is this what you meant?

    Now, I have never coded JDO, but I have read about, looked at the sample code, same for ObjectRelationalBridge and used the ODMG api a log, so I am not an expert and am trying to be as careful as I can about what I say. What I wanted to do was learn from other people who have used it before.

    Cheers,
    Mike.

  53. Why I hate Entity Beans[ Go to top ]

    Mike,

    Well you can't map 2 different kinds of objects to overlapping subsets of the same table. You're going to have problems w/ object identity clashes or even worse inconsistent data.

    I'll be honest, I haven't worked with JDO, but I've worked with ODMG. So I'm basing my opinions on what I know about ODMG (after all JDO is just a "cleaner" version of JDO). My experience with ODMG hasn't been pleasant.

    Also, I'm currently working with ObjectRelationalBridge (OJB), but I'm sticking with the core layers. I just think the ODMG and JDO api's are completely hokey and aren't based on solid foundations.

    Carlos
  54. Why I hate Entity Beans[ Go to top ]

    Carlos,

    >Well you can't map 2 different kinds of objects to
    >overlapping subsets of the same table. You're going to
    >have problems w/ object identity clashes or even worse
    >inconsistent data

    But wont this will only be a problem if the overlapping objects execute in the same transaction? This kind of behaviour will happen no matter what kind of O/R layer you are using. Is this what you mean?
  55. Why I hate Entity Beans[ Go to top ]



    Carlos,

    I found it easier to understand the value of JDO when I compared it to JDBC. I feel that JDO is much more a competitor for JDBC than Entity Beans (though, obviously it reduces the value proposition of entity beans)

    JDO doesnt provide declaritive transactions in the same way that JDBC doesnt. However, a JDO implementation will be JTA aware - so that if used from a session bean or from a BMP bean, the transaction will be declared on the EB/SB...

    For the record, I dont believe in transparent persistance (just as the same as I dont believe in location transperancy when it comes to distributed computing) - so I kinda have some doubts as to the objectives of JDO...

    -Nick
  56. Why I hate Entity Beans[ Go to top ]

    If you want an exhaustive list of problems with EJB and Entity Beans we rung the towel dry.

    http://www.softwarereality.com/programming/ejb/index.jsp

    We realised most of these issues when writing a code generator - called JGenerator. There are demo's on our web site http://www.javelinsoft.com/jgenerator that show how it works.

    The bit I (and most others I've talked to) find upsetting about EJB's is that I actually like the general thrust of the client API's Session, Home, findBys() etc. I find the unnecessary requirement to implement all the server details along with the APIs intellectually unfathomable.

    JGenerator takes these API's and can generate In-Memory, File, Jdbc, JDO and EJB implementations under the covers. So it shows you that it is not difficult to de-couple bean architectural interfaces (Sessions and Homes) from the actual implementation. This means you can mix and match your implementation for different entities depending on your specific requirements.

    One size does not fit all - never has, never will.
  57. Why I hate Entity Beans[ Go to top ]

    You may want to take a look at my JDO-related article in JavaWorld:

    http://www.javaworld.com/javaworld/jw-03-2002/jw-0301-jdo.html

    http://www.javaworld.com/javaworld/jw-04-2002/jw-0412-jdo.html

    One of the paragraphs compares JDO and CMP also...

    -- Jacek
  58. Why I hate Entity Beans[ Go to top ]

    If you are using IBM WebSphere Studio Application Developer tool then developing EJBs is the same as developing Java Beans. And BTW - testing is even easier since it generates for you dynamic interactive test client. That is really cool stuff. You don't have to mess w/ many interfaces, DDs, etc. All done under the covers and that IS what EJB spec assumes. I'm amazed that people do J2EE development by hand.

    J2EE spec was designed in a way so development can be facilitated by tools (automatic generation of artifacts instead of tons of monkey work) and those who use Notepad (or vi or SlickEdit and alike) - waste their time and money.
  59. Why I hate Entity Beans[ Go to top ]

    You mention the burden of creating and maintaining so many support files for entity beans. Have you tried EJBGen? It is a new EJB generation tool that requires you to maintain only a single file and all other files are generated.

    It makes beans extremely simple. Here's the link: http://www.beust.com/cedric/ejbgen/
  60. Why I hate Entity Beans[ Go to top ]

    The system I'm currently working on is an extremely large, complex enterprise application. It has a web front end, and uses nearly 200 stateless session beans. These beans use custom classes similar to JDO to access the database. All of these use the Value Object J2EE pattern to cut down on method invocations. It does mostly viewing of data with some modification.

    Unfortunately, some small number of these objects are fetched very frequently, causing us scalability problems due to heavy db usage. The database CPU usage was low, but the network latency and the resulting garbage generation was the source of our scalibility problems. Using JProbe we discovered that most of the garbage that we were generating came from the Oracle JDBC driver! All that marshalling/unmarshalling of fields was a killer.

    We got dramatic improvements in performance and scalability by using bmp entity beans to front those select number of objects that were fetched very frequently. Since the entity beans hold cached values, we avoided the massive garabage generation and network overhead for these particular objects.

    This also gives our customers the ability to adjust the cache size, etc, of these beans, via a standard mechanism, the deployment descriptor. We use JBoss and Weblogic which both have settings to tell the container it owns the data. The container then can keep the bean in memory and avoid an ejbLoad.

    So I'm not sure how one would solve this without entity beans. They provide the caching and have transaction knowledge to know when to refetch. Does someone know a different solution to this problem? I think this is an important case for entity beans.

    Don't say, don't get those objects so often! It would make our APIs very cumbersome because we'd have to have nearly double the number of methods...one method which takes an id of a referenced object, and one method that takes a value object of the referenced object.

  61. Data Object Caching[ Go to top ]

    Hi Michael,

    Our experience in profiling our J2EE apps has also been that it's the persistence layer (including DB) that eats most of the time. JDBC and O/R mapping are expensive. Like you, we've also found that improving our design to touch the db less makes the biggest difference to performance. So I think you've pointed out a major design issue: a transaction-aware cache is very important, and is an important desirable feature that entity beans have.

    But... you said that you use custom classes "similar to JDO" to access the database. I'd expect a commercial JDO implementation to include such caching, just as entity beans do. Of course, such caches may not be distributed - but if your transactions are 'sticky' (ie a single transaction stays in one app server instance) that shouldn't be an issue.

    Could someone with better knowledge of JDO please either confirm or correct that expectation of mine?

    Do the non-JDO O/R tool vendors (hi, Ward) also want to comment on the caching issue?


    Sean
    PS: 200 session beans!!! Good God!! Our projects typically involve 10 to 15 j2ee-developer-years, plus the analysts, testers, managers, users on-site, etc, and we're usually closer to 20 or so components, ie 20 or so session beans. Just how big is this "extremely large" Behemoth of yours?
  62. Why I hate Entity Beans[ Go to top ]

    I have been reading this post with interest. I will admit I don't have very much experience in dealing with technologies that mimic the database in an Object model. We are converting off of a system that uses a mix of BEA Tuxedo and Oracle PRO/C for creating "services of business logic." I actually like this idea of units of work, forgetting using C of course. One idea we are proposing at work is using Stateless Session beans that have SQLJ code in them for our business logic. That way we will have an easier time to develop by using Java than C, have the benefits of using an application server (JMS, Resource Pooling) and yet still be able to code our business logic in a manner we are used to "Plain Old SQL". The system we deal with has hundreds of tables and sometimes we do triple or quad table joins. What would we gain by going to an Entity EJB system other than a training nightmare for 70+ people? Please respond here or email me personally at cdog1977 at hotmail dot com I would be interested in getting people's opinions with greater experience than mine.
  63. Why I hate Entity Beans[ Go to top ]

    "SQLJ code in them for our business logic"

    You code your business logic in SQL?

    You may not want to EJBs for all or anything. You may want to mix and match.
  64. Why I hate Entity Beans[ Go to top ]


    Here I refer to CMP generically - to mean CMP Entity Beans or JDO.

    Depending on your complexity, CMP may not at all be possible for *some* of your cases. The question is: How much of your database access is *that* complex (the multi-multi-table joins you speak of) that CMP could not work. Pick the solution that solves the majority of your problem (rather than that wich solves the 5%).

    The mistake some people make is that they feel there is a binary decision to be made: CMP or JDBC. You can use both. I always start with CMP until it doesnt fit - but know your container. Not too many people really know what a good CMP container can do for you.

    In many cases, you can get by with the Entity Bean CMP engine your appserver gives you (weblogic 7's is reasonably feature rich). In some cases, you can improve performance/flexibility of CMP simply by adding a good persistance manager (Such as Toplink - now owned by Oracle - or Cocobase, ObjectFrontier etc) and you wont have to change any code.

    In some of these cases, the performance gain that you get from using these products - the caching, tuned updates / batched updates, lazy loading, eager loading are not so easy to get when using "Plain Old SQL". Caching especially so.

    The real benefit in this case is that optimising your database access can be as simple as tweaking some settings. Your hardened database programmers will be the best people to appreciate what the tweaking will give them. And when you do this optimisation, you can do so with a fair degree of confidence you will have ZERO debugging to do (definitely NOT the case with roll-your-own persistance)

    Hard-core SQL-ers have a hard time accepting CMP solutions. Just as C++ programmers found it uncomfortable letting go the reigns on memory management when moving to Java, so too do many old-school "database programmers" find it hard to trust the generation of mindless SQL to a piece of software.

    I would say that your best bet is to slip in slowly. A training course for 70+ developers sounds like a disaster waiting to happen.

    Take aside a small team of about 3-4 willing and able developers (a mix of experience and open-mindedness is important) and let them explore the boundaries of using Entity beans or JDO. Build on the success of the pilot to spread the change. Start with a good CMP2.0 implementation - Weblogic or Borland Appserver (Websphere is still on EJB1.1 until at least August/September). Dont waste your time on CMP1.1.

    -Nick

  65. Why I hate Entity Beans[ Go to top ]

    Hey Nick, don't forget JBoss in your recommendation to Carl. JBoss 3.0 has a CMP 2.0 engine and its free and open-source.

    BTW Carl, you could get training for your 70+ developers and consulting and support from JBossGroup for about the same price you would pay for your Weblogic or Websphere or Borland licenses and support.

  66. Why I hate Entity Beans[ Go to top ]


    No, and JBoss too ;-). I havent had time to check up on JBoss lately. Their 3.0 seemed to take forever to turn out - and there was some question as to whether they had nailed their CMP2.0.

    If you do have a look at JBoss, make sure that you shell out for their documentation - you will struggle without it.


    -Nick
  67. Why I hate Entity Beans[ Go to top ]

    Just one last notion. Some are saying that JDO will never get into J2EE and that will be an obstacle to its adoption. And them some say that JDO compliments JDBC more than it does Entity Beans. So maybe JDO will be made part of J2SE? The would be kinda nice.