Using DAO pattern - java

I am trying to use the DAO pattern in my multiple web app projects. I have three different web applications and they share two different databases. Each databases have number of tables.
Now I am wondering how I can make my program modular by using best practice. I am thinking of making:
DAO project which have two factory class for each database, DAO interfaces for each tables and DTO for each tables.
Then in each web app project I am planning to write implementation code for DAO interface and necessary utility class for getting and closing the connections.
Is this approach good? The doubt/problem i am having is with this design if I am going to ship any one of the project I have to ship DAO project also but that will contain unnecessary info about other databases.
Or will it be good to attach all necessary DAO in web app itself? If so then I have to write same DAO ode for each web app.
Hope anyone can provide me the clear path for this DB connection using DAO pattern.

In general, you're headed in the right direction by separating your concerns.
You mention the multiple web apps rely on the two databases. Does each web app rely on both databases? If so, I'd consider creating a single DAO project to encapsulate all the data access logic.
If it's more a mix and match (web app a uses db a, web app b uses db b, web app c uses a and b), I'd consider having two DAO projects, one per database, unless there's a lot of combined logic - that is, when an app uses both databases, it's doing joins between them [yes, I have had projects that do this].
I'd also recommend looking at an Object/Relational Mapping (ORM) framework such as Hibernate and/or a Dependency Injection framework such as Spring, which can help simplify the process of separating the various projects and then using them together.
You're clearly planning a pretty ambitious project, so taking advantage of existing frameworks to minimize recreating the wheel will let you focus on your specific problem domain.

Use JPA to access DB. If not possible then use JdbcTemplate (Spring)
EntityManager (JPA) is a kind of a DAO
DAO only where it makes sense (e.g. complex, reusable logic using an EntityManager)
Use pooled connections/ DataSources
DTO are usually only needed if your objects need to leave the JVM (e.g. remote EJB services, web services,...)
use EJBs for container-managed transactions
consider the Gateway pattern (a stateful session bean and an extended persistence context, see "Real World Java EE Patterns – Rethinking Best Practices" by Adam Bien) and just return the attached entity.

Related

Passing Presentation Modal objects to the service and business layer

I am developing a web application using struts2 EJB3(Service/business layer) and Hibernate. I am using Wildfly 10 as a server. Struts is at presentation later, EJB3 at business layer along with simple java classes as Service layer and hibernate is used in persistence later.
Now in one of my action classes I have passed the modal object to the service layer(Simple java classes). Now when I created the EAR and tried to deploy it on the WIldfly. WIldfly refused to start. Then I realised that my ejb module is not able to find the classes of web module. So now I have two ways to resolve this problem:-
1) Either include my web classes in EJB jar:- I think it will completely kill the layered architecture and decoupling of presentation layer and service layer.
2) Or map the modal classes to some other modal classes present in service layer:- It will require to create redundant POJO classes in service layer as well.
Not really know what should I do in this case and if someboddy can suggest me with some better layering structure
There are serveral ways you can architect your models for each layer but at the end of the day, it depends on how much you wish to couple each layer with one another.
Obviously the most granular and cleanest solution is to allow each layer to have its own models and to map accordingly at each integration point.
Persistence models, e.g. your #Entity classes
Domain models, e.g. those your service tier takes as input and returns as output.
View models, e.g. those your presentation tier takes as input and returns as output.
The advantage of such a distinction is that it allows the models at each level to morph over time without a significant impact to the tiers above it. In other words, adding a new field or changing something with your persistence model doesn't necessarily mean your domain models must change, but just the mapping code between them.
Obviously there are a number of sources on the internet which advocate simply reusing your #Entity classes as the model at each tier and for simple applications, that's definitely acceptable. But in more complex, scalable solutions that eventually becomes a liability.
Sometimes it's acceptable to collapse (1) and (2) into a single model, the #Entity and then use special view models for rendering so at least your view code isn't impacted when you make model changes over-time, but I typically err on the side of using a different model for all three tiers in many cases for complex applications.

can JPA eclipselink be mapped to REST service?

Nowadays typical JAVA application can expose some JPA entities via REST easily. In that case in short there is e.g. persistence.xml where driver, database, etc are defined to access the database and persistence unit easily can be used in the application.
I am looking for something opposite. I.e. if somebody saw the solution where persistence relays on REST API?
Background of my question is the following.
There is an app written in some ancient technology and there is quite complex logic behind. I would like to build new JEE JPA (Eclipselink if possible) based application which could (at least for some time) use that complex logic in order to find and read data. My idea was to implement REST interface on top of old application and let the new one use REST queries in order to deal with the data. Since logic is complex I would like to avoid duplicating it and maintaining 2 branches of code in different technologies until I am fully prepared to move all stuff into modern technology.
Do you think it is possible?
You can design your Data Access Layer and the rest of your new application so that it doesn't care how the data is stored (no "bad" dependencies).
You would then need to create separate versions of the DAL, where one would fetch the data from the legacy REST app and one would use JPA. This will make it possible to start out being dependent on the legacy app, and part by part build the JPA DAL to retrieve data from a database.

Differences between Spring Data and JDBC/ORM modules

I'm starting a new Java Web project using Spring and obviously I need data access in my application.
In previous applications I used JDBC or ORM modules of Spring framework to implement my data access layer, but some times ago I read about Spring Data project. I'm curious about it and I'd like to know the diffenrences between the two projects and understand if there are advantages passing from one approach to the other.
Spring data provides several functionalities:
Common functionality related to database applications - Defining a "repository" element (similar to DAO) with various functionalities, audit trail, etc.
JdbcTemplate like support for various NoSQL databases - MongoDB, Redis, Neo4J, and there are several community projects for other databases
High level functionality for JDBC (mostly Oracle) and JPA to reduce boilerplate code
Spring data also aims to save boilerplate code, as the repositories are defined as interfaces and the implementation is given by spring based on the method names.
Spring Data use JPA. it is also great for reducing the amount of boilerplate code that you need to write.
By writing the interfaces
E.g. table.findAll()
Its uses aspects to create the boilerplate code to select * from table
or table.findByName
it will implement the code to select by Name
have a look at this excellent tutorial http://www.petrikainulainen.net/spring-data-jpa-tutorial/

Multiple DAO's vs One DAO with configuration file

I'm currently in the process of creating a data access layer for an application. This application will initially connect to an Oracle database but will later also connect to a DB2 database.
For connecting to the database I will use JDBC. At this time I'm considering my options. As I see it I have two (primary) options.
1) Create a design with support for multiple DAO factories, each instantiating the DAO's specific to their database. Initially, this design will only have one factory. Later it will be extended with a second factory and DAO classes.
2) Create one DAO factory which instantiates multiple DAO's for the different models. This DAO factory builds the DAO's based on a configuration file, which contains the JDBC driver path and connection url.
I'm tempted to choose the second option, which seems to remove quite some code duplication in the DAO's. Could anyone give the pros and cons of both approaches?
Why would you choose for multiple DAO factories (abstract factory pattern) when you don't really need it when using JDBC?
I believe Spring or Guice would be the best and cleanest option for you, where you'd want to pick the appropriate DAO implementation and inject it in the DAO consumer layer. Spring will also enable you to use Spring-JDBC which takes care of most of the boilerplate code making your DAO Impls easy to manage and code. You can also use ORMs with Spring.
Taking into account that you can't use Spring (even though it would save you from a lot of coding), I would say that 2nd variant is more appropriate to you, because you are going to implement dependecy management yourself and 1 dependency (single DAO factory) is always easier than 2.
Though, if you expect that amount of places were DAOs for both databases are used together is not big, then separating them into 2 factories will have a better structural meaning and is more clean. But if you expect, that pretty much every class that uses DAOs will need both worlds (Oracle + DB2), then again stick to the 2nd variant.
In any case, try to consider again about dependecy injection framework usage, because that what you are going to implement yourself anyway with all your factories.

Do aspects substitute repositories?

I started experimenting with Spring Roo just recently. It does a very nice job helping one build a domain model with integrated persistence rather quickly. As it adds persistence functionality in aspects, I started think about the following question:
Roo adds finders (load an instance of a class from the database which meets variable criteria) in an aspect to the actual class/entity. In DDD this is IMHO the responsibility of repositories. Repositories are explicit classes which show up in the design. Of course as an aspect the repository functionality is hidden in an entity and is pretty much invisible.
So here is the question: Is an aspect a real substitute for a explicit repository class? Are there any downsides to the Roo AOP approach?
Adding finders to your domain classes feels more natural from a user's point of view but it mingles your layers. Grails uses the same approach by adding static finder*() save(), ... methods.
Apart from the aestetics it might have practical drawbacks when not used in web application setting:
Your domain classes are now tied to your database. If you transfer these objects to rich clients via RMI or HttpInvoker the client cannot and often may not use the find* methods because there is no session / database connection available on the client.
I generally prefer allowing domain classes to reference service layer interfaces to prevent an anemic domain model (http://martinfowler.com/bliki/AnemicDomainModel.html). This has its own set of drawbacks but at least provides a clear boundary. On the client the concrete implementation behind a service interface can then just proxy all method calls to the server (or just use a synamic proxy with spring remoting or sth similar).
So to answer your question: It might be a substitute but you should be aware of the possible negative consequences which make your domain classes (i.e. your core business logic) less portable between systems.
This depends on how complicated your applications persistence layer is and how much control you have over it. If your application is simple enough to be implemented via JPA, then it all could be handled via Roo aspects. However if you are mapping legacy tables or need advanced DB stuff, then you may find yourself in a situation where Spring-JDBC is the only way out and in these cases a repository/dao model may still be useful.
I consider it logical inconsistent (and a break of layer responsibility) to be mixing two persistence models and so as most of my applications requires such advanced DB constructs I stick strictly with a repository model.
I think adding repository methods to domain objects is bad design. The right place would be static methods in the domain class. But domain objects and their management are two different things that should be separated. I would prefer domain objects and repositories.
I guess the motivation was to achieve something Rails/Grails like with Java.

Categories

Resources