Usually when defining a DAO, you would have a setter for the datasource on the DAO object.
My problem is that our datasource varies dynamically based on the request to the server. i.e. every request can access different database instance.
The request holds logical properties, that later can be used to retrieve the connection to the DB of the request.
So when dependency injecting the DAO to the business logic object, I need a way to set the properties on the DAO at runtime (not configuration time).
One solution is to store the datasource on the thread local, but I don't really like messing with thread local variables.
Another option is to have an initialize method on the business logic object that calls initialize on the DAO with the request properties.
I guess it's a common problem, can you suggest a common solution?
Your problem is a little confusing. Having one DAO access multiple different datasources would seem to be a maintenance nightmare. As a result, you should define one DAO interface containing all the methods you would want to call. For each database you are connecting to I would construct a new class that implements your DAO interface. This allows you to have multiple implementations. I would then store these implementations (each that has its own datasource) in a Map (java.util.Map), using your "logical properties" as the key to the map. Since all your DAO Implementations implement your interface you will be able to cast them to the interface and use them interchangeably. On your business object, you would inject the Map of DAO implementations. I hope this helps your design.
I had such a problem on a client/server project. Client and Server projects was sharing Dao interfaces. And When I used to do database operation I had to select suitable Dao implementation. My solution was like this :
IVehicleDao vehicleDao =daoFactory.Get<IVehicleDao>(parameters);
vehicleDao.doSomething();
Get dao from Factory by passing parameters.Inside Dao factory decide which Dao implementation to return..
You may want to look into this class:
http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/datasource/lookup/AbstractRoutingDataSource.html
This will make it easier for your service objects and data access objects to be ignorant that any notion of dynamic datasources exists.
Typically you'd need to implement a servlet filter and use a ThreadLocal so that the DataSourceLookup implementation used by AbstractRoutingDataSource can easily gain access to the request parameters that dictate which DataSource is returned. If you really want to avoid that, you could implement a servlet filter which sets properties on a request-scoped bean and inject that bean into the DataSourceLookup implementation you've written. Request-scoped beans still use a ThreadLocal in their implementation but at least this way it's Spring's impl, not yours, and you don't need to worry about it. :)
Similar approach is detailed in this blog entry from the Spring team:
http://blog.springsource.com/2007/01/23/dynamic-datasource-routing/
It sounds like your problem is that you are creating a single DAO instance for your application. You either need to create a separate instance for each datasource (maybe making some kind of dao controller to manage it all for you) or possibly allow your methods in your dao to be static and pass all information about how to connect to the datasource along with the data you are persisting into every method.
I already did this. You need to create one DAO each class, and in the scope of your DAO you need to pass the DATASOURCE and finally one class CONTROLLER where you do dynamic calling to DAO.
Related
I'm building a web application that primarily constitutes of CRUD operations of data from back end/database. There are instances where in I have to write business logic(I'm sure we will have more business logic built as we go deeper in to development). Currently for each UI screen I'm creating I create a model class,Service class, DAO class, a controller(it's servlet essentially) and bunch of jsp pages. In most cases the service class just calls the methods from DAO to pass in model objects. Essentially we use model classes to map data from UI screens. Hence the controller will have the model objects populated when a form is submitted. I have started using service classes to keep a separation layer from web layer to DAO layer. But at times I feel that the service class is just adding unnecessary level of API calls, I would think that I could just inject the DAO in to Controller and complete the task faster. I want to use the service class only when there is additional business logic to be performed. If you have to design an application what factors do you consider using controller->DAO vs controller->Service->DAO control flow?
DAOs are more granular and deal with one specific entity. Services provide macro level functionalities and can end up using more than one DAO. Typically, Services are used for defining transaction boundaries to gain atomicity. In other words, if you end up updating multiple tables using multiple DAOs, defining transaction boundary at service will help in either committing or rollbacking all the changes done to DB.
In your design, since you are primarily doing CRUD for various entities, it may seem that services are not adding much value. However, think of web-based front end as one way of updating data. Usage of services will allow you to expose same capabilities as a web-service later to other forms of client like third party integrators, etc.
So, in summary, your design seems to be in line with conventional practices. If you feel that you can combine multiple services into one based on some common theme such that it can reduce the overhead of code, then, you should go ahead and do it. At the end of day, ultimate goal is to create maintainable code which no one is afraid to change when need arises.
In Pro-Spring-3 book they mentioned below line, for controller with JPA2
Once the EntityManagerFactory had been properly configured, injecting it into your service layer
classes is very simple.
and they are using the same class as service and repository as in below:
package com.apress.prospring3.ch10.service.jpa;
// Import statements omitted
#Service("jpaContactService")
#Repository
#Transactional
public class ContactServiceImpl implements ContactService {
private Log log = LogFactory.getLog(ContactServiceImpl.class);
#PersistenceContext
private EntityManager em;
// Other code omitted
}
but in case you are going to use spring-data CRUDRepository or JPARepository then your DAO will be Interface and you have to make service layer to handle your code
I'd reference my answer here
The long and short of it is the advantage of using a Service layer is it gives you room to move in the future if you want to do anything with Spring Security and roles etc. It allows you to handle transactions more atomically and Spring itself has really nice annotations for this.
Use a service class when dealing with more than one aggregate root.
Inject repositories (aka a dao that returns a collection) or dao's directly into controller, no need for an extra layer/class to do a basic get.
Only use service classes where necessary, otherwise you have twice as much code as required.
You can make repository generic, and annoatoate with #Transactional(propagation = Propagation.REQUIRED) which enforces a transaction is present, but won't create a new one if already present. So if you later use multple repositoes in one service class method, you will only have the one transaction.
I have always used the DAO pattern for CRUD operations, each DAO in charge of accessing to a unique datasource at a time, and use generics to support multiple entities.
Now I require the same with the following changes
1.- Datasources will be added/removed dynamically at runtime
2.- A unit of work involve for instance: reading from datasource A, writing on B and deleting from A if B succeded. A and B will be interchangeable, which makes me think of some sort of origin/destination mechanism.
3.- Reads will only be done against 1 datasource only
The entities will be the same in all datasource, for which I could add a factory that creates a new DAO whenever a datasource is added, answering the first question. But I'm not sure how to address the rest.
Is the DAO pattern still suitable? If it is, what needs to be added? Or is there a different approach to this as a whole?
If Spring is part of your application stack, You can use AbstractRoutingDataSource which will give the flexibility to add dynamic datasource mapping. If not go through the source code of it and you can build your own logic something similar to this.
On a quick google, I come across this http://blog.springsource.org/2007/01/23/dynamic-datasource-routing/.
It is explaining this dynamic routing in action.
This sounds like a business transaction. You need a business component covering the transaction, which involves multiple DAOs.
I have a Java library where I access the DB via JDBC using Spring's JDBC support. This library contains approximately a DAO class for each table I need to access, which are over a hundred. Currently I instantiate a new JdbcTemplate, or one of its variants, each time I need to perform a new query. Is this considered good practice or should I reuse a single JdbcTemplate as much as I can? I've actually seen examples of both approaches in either books or online documentation.
The context is a J2EE application, but ideally the code should be usable in different contexts, e.g. in offline tests or command line support tools.
Inject one, why bother instantiating? (It's unclear if you mean "instantiate through the Spring context" or "instantiate using new".)
Most samples I've seen do this in the config, I'm not even sure I've seen them instantiated manually outside of demo/test code. I see little benefit to doing it manualy, and zero if done outside of Spring.
Although there isn't a lot of overhead involved in creating a new JdbcTemplate, there isn't much of a point. The JdbcDaoSupport class, an abstract class useful for handling JdbcTemplate based DAOs consistently allows each DAO to either inject a DataSource (and undernear the covers instantiates a JdbcTemplate based on that DataSource) or inject a JdbcTemplate. Since you can do either you would only do the latter if you were looking to customize your JdbcTemplate by setting one or more of the following properties:
fetchSize
ignoreWarnings
maxRows
nativeJdbcExtractor
queryTimeout
skipResultsProcessing
exceptionTranslator
You would likely have one JdbcTemplate for each combination of these properties. All of these do have defaults, so its only necessary to set them if you are going to override them. Depending on the diversity of your DAOs, you may have one or many. Or in the case of extending JdbcDaoSupport, you may have none, having each DAO just wrap the datasource in a default JdbcTemplate undernearth the covers.
Instances of the JdbcTemplate class are thread safe once configured, so you can configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs (or repositories). For more information: JdbcTemplate-idioms
Obviously using stateless EJB beans in an entity bean smells, but please consider a scenario as follows and tell me if you know of a better solution:
I have an InvoiceTemplate Entity Bean with field NextInvoiceDate
Generating NextInvoiceDate is a complex procedure and should be performed outside of the InvoiceTemplate class
NextInvoiceDate should be updated each time InvoiceTemplate is stored to the db
For now I have logic regarding the generation of NextInvoiceDate in #PrePersist #PreUpdate methon in InvoiceTemplate entity bean. The logic is getting more and more complicated and I want to move it outside of the InvoiceTemplate entity bean. It looks to me that there should be a service to calculate NextInvoiceDate. But then is it right to invoke this service from the inside of InvoiceTemplate?
It isn't such a smell - it is a lean towards domain-driven design.
I don't know of any way to do this automatically, but you can:
in the session beans where you handle your Invoicetemplate, inject the helper bean that has the logic to calculate the next date
create a private field with a setter on the entity, and before you start using it call entity.setNextDateHelper(..)
You can also check whether AspectJ doesn't offer some EJB options so that you can inject the EJB whenever an entity of a given type (InvoiceTemplate) is created. AspectJ works like that with spring beans, I don't know whether there are such options for EJB.
Do you need anything as complicated as a service or EJB? Can you just write a static method (possibly on a utility class) to hold the logic? Normally I'm pretty biased against this sort of thing, but if all you've got is some complex logic that doesn't require any DB interaction or a lot of object collaboration, it may be the cleanest approach.
I have seen two ways of implementing DAO-DVO design.
1) DVO are objects and DAOs are instantiated using factories i.e DAOs are also objects
2) DVOs are again objects but in this case, DAOs are classes which contain only static methods which accept DVOs to perform tasks.
I was wondering which way is better and more scalable.
Try the Spring Framework. DAOs are initialized via Dependency Injection and are just plain 'ole Java objects.
Then, the methods on the DAO should just use Domain Objects that are used at all layers of the Application.
With regards to testability, I'd advise against the second approach. Static methods prevent you from adjusting the class's behaviour by overriding collaborators with mocks and such. As Miško Hevery puts it: "Static Methods are Death to Testability".
I would strongly recommend not using that many layers unless they are really layered physically. eg if you have something like a rich client where you need to send detached objects to update the GUI, otherwise, its a world of pain.
How to download DAO Factory to create Database Connectivity?