I'm fairly new to Struts. I've read probably just enough to get an app going. I've been writing a database driven application. I am not trying to rag on Struts, but I would like to learn good design.
I have a model that connects, queries, and returns data in the form of beans to the controller. Then from the controller I copy the data into a form or just pass it into the view as an attribute. The problem is there is very little application logic. Maybe some code to update the database. I can pretty much just copy the model code over and over. "Connect, Query, Return" or "Connect, Update", etc. It's quite a bit of work to do something so simple. It is becoming very tedious.
Am I doing something wrong? Am I missing something?
Are there good sample code out there demonstrating a "real life" type application?
First of all, let me say that even though Struts is a framework that follows the Model/View/Controller (MVC) pattern, the components and helper classes it gives you are all in the View and Controller layers. In a Struts application, what you do with the model classes is pretty much up to you. Since your question is about how to write classes that access the database, you're talking about classes in the model layer.
If you decide to use the traditional approach and write classes that use JDBC to access the database, the most important thing you can do to eliminate tedious duplication is to use good principles of object-oriented design: Find code that gets repeated a lot and push it up into a super-class or helper class. Find ways to write methods that are more generic that have a greater capacity for reuse.
If you're putting code that accesses the database inside your Action classes, the first thing to do is refactor and put this code in other classes. I'd suggest using the Data Access Object (DAO) Pattern.
Another approach would be to use one of the object-relational mapping (ORM) frameworks that are becoming popular such as Hibernate, JDO, and others. In these frameworks you use XML files to indicate how your classes map to tables and rows in the database. The framework then handles writing the JDBC and SQL code that actually accesses the database, and in your code you call APIs to the framework.
If the structure of your object graph is fairly close to that of your database schema, these frameworks work pretty well, and can save you from writing a lot of tedious database access code. If your object graph does not match the database schema very closely, it has been my experience that you're better off sticking with writing your own JDBC code, as you will spend as much time trying to get around the restrictions of the ORM framework as you would just writing the JDBC code yourself, and in the end, the JDBC code you write is going to be more efficient that what the ORM framework generates. [ April 23, 2006: Message edited by: Merrill Higginson ]