I access a REST API to get some objects in order to save them in a local DB. Later I want to access these objects in the local DB and update them as well.
I'm not sure what is the best way to go - trying to use the DAO Design Pattern. What I see is, that there are different data sources for different cases (operations).
Can you give me some ideas?
First advice: do NOT overcomplicate your solution if it's not necessary.
If you are using the same DB instance for read and write operations, just create single pair of the DAO interface\implementation for all operations
Additionally, API call should NEVER reach data access layer directly. Add business service layer in between.
API -> Business Service(s) -> DAO -> DB
Related
I need to make a REST API so two components can communicate with each other.
The flow starts like this:
Component 1 sends a request
The API processes it and, if everything's correct, writes inside Component 2 DB
Various data processing...
Component 2 sends a request
The API processes it and, if everything's correct, writes inside Component 1 DB
How do I make this appen in Spring Boot? I don't need any domain class, so I don't think I need to use JPA.
Update: I need to make it work with JdbcTemplate
Thanks in advance
I'm not sure what you intend to achieve here but this is what I would suggest you do if you really need to achieve this with JDBC template.
In your configuration file: e.g application.properties, you could specify keys to hold values used in configuring every different connection to the databases you need to interact with. A naive example could be:
app.datasource1.url=...
app.datasource1.driver=...
app.datasource1.username=...
app.datasource1.password=...
app.datasource2.url=...
app.datasource2.driver=...
app.datasource2.username=...
app.datasource2.password=...
You could create beans of these connections in a config class and differentiate them with names (qualifiers), one of them could be a tagged primary data source and the other a secondary data source. As an alternative, however, you can do 3 each time you need an instance of the DB connection.
Since you are using the JDBC template, in the service classes or implementations where you make calls to the database, you could start first by creating a connection (an instance of JDBC Template) before using it.
With this approach, you can create as many connections as you want to as many DB as you want. Don't know if this helps.
If I have a Database(DB) containing two tables/entities (A and B),
should I make a DAO for each entity? (Ie DAO_A and DAO_B), Or do I make a DAO for the whole DB containing these two tables?
Then as regards the repository, will this be a repository for the whole Database(whole of DB) or just a repository for the database with only the relevant DAO's I want the class for (ie DAO_A and DAO_B).
(Realy what I think I am asking here is will the Database have multiple repositories or just one repository, and will each entity have to have its own DAO, or can I make a general D
I would say go for every entity has its own DAO. Why? Because you properly separate them.
Let's say you would have a DAO which contains Entity A and B. In your repository you might only need Entity A, then it would not make any sense that this DAO uses Entity B as well. If a case occurs, where you need both Entities, just use both DAO's. A further reason for seperate DAO's is that you don't know how to couple Entities properly. How are you going to decide which Entities to couple into a DAO? Yes you could decide this depending on the Repository which makes use of it, but this can lead to code duplication (two DAO's make use of the same Entity, but each of those also use a second one - which is different for each DAO).
Regarding your second question: I believe it depends on your architecture how exactly your repository should be modeled.
For example when using MVVM:
Requirement: You have an Activity just displaying a list of images fetched from somewhere.
Then your ViewModel would offer a function like getAllImageModels or something similar. Each of those ImageModels would include an image (which will be displayed). Inside this function the Repository is called either an API call to retrieve a list of images to download or a database call to retrieve the list from the database (depending on internet connection). These images must be downloaded as well. Again images could be loaded from your local cache or downloaded via the API. Then the ViewModel wraps them in the desired model required by the View and thats it.
As you can see by this simple example, the Repository on its own just performs requests. Either to the local filesystem, database or API. It could have functions like getImageListFromDb and getImageListFromAPI in it. So that the classes which make use of it just have to decide when to use what.
This question is related to the core understanding of the Java DAO Pattern. Please look at a simple java dao pattern example to understand my question.
At line 2 below, the student object has already been altered with a new name, what is the point of line three if both the client and the backend are running under the same JVM?
In my humble understanding of the DAO pattern, the client must only alter data using services, such as the studentDao below, and the client shouldn't have the possibility of altering the value object (pojo) directly. But when both the client and the backend service run under the same JVM, and client gets a POJO with normal setters, why does the client need to call the service?
Are there any best practices to implement a DAO pattern where the client can and must only consume/alter data using dao-services? A very example would be great to look at.
//update student
1. Student student =studentDao.getAllStudents().get(0);
2. student.setName("Michael");
3. studentDao.updateStudent(student);
well, what does it mean on same JVM. If your DAO uses DB, then the object won't change in DB when you change POJO. Similarly, when other thread will load the same entity, the new POJO will be created based on the DB content (unless your DAO makes some special caching) => no problem.
So for now let's assume that you build some kind of in-memory DAO. If not implemented properly, in such case change on POJO can "effect" other clients as you have already pointed out. However this is not good implementation of DAO - so you have to take care that POJOs accessible by clients can't have impact DAO "state". The easiest way to do so is always return defensive copies for both all returned values but also for all inputs (insert, update etc).
I have design issue when implement 1 simple web application.
I use struts2 web controller, spring’s IOC and Hibernate as persist layer.
Because this web application is very simple at begging. So I only have 2 layers:
1 DAO layer which used to access database. Almost every table have related DAO.
2 Action layer. User struts2.
I am satisfy with this architecture because can quickly implement my web application.
As project become bigger, I found the action layer become big and complex, and very hard to re-use.
I try to create service layer, to solve complex business logic is good, but my application still have a lot of simply logic. E.g: Load 1 object, save 1 object, and get collection by some condition and display it to webpage. If give each simple DB access method have corresponding service method. Still cost a lot of effort. How can solve this issue?
And I think, if service layer existing, direct call DAO layer still not good design for my application.
Is any good solution for this kind of small web application?
When planing the different layers in a web application it is good practice to explicitly protect attributes and associations in your model from being manipulated without providing an identity context.
This is something that should neither be done in the DAO layer nor in the Controller. You should wrap your DAO layer in a service layer and have the controller only talk to the services not the DAO directly.
Protecting your model against unwanted manipulation means that you for instance adapt the amount of information passed in a data structure between Controller and Service to the actual operation that you want to perform.
For instance: adding or removing an element from a collection is an explicit operation in the service, it does not happen implicitly by manipulating a collection as a member of a DAO object and passing that DAO back into the service.
Instead your service may look like this:
+ getAllCompanies(): CompanyType[*]
+ getAllEmployeesOfCompany(c: CompanyType) : EmployeeType[*]
+ addEmployeeToCompany(e: EmployeeType, c: CompanyType)
+ removeEmployeeFromCompany(e: EmployeeType, c: CompanyType)
The additional benefit of such an architecture is that the service layer serves as boundary for your transactions. Using the methods of your controller as boundary for your transactions is in fact a very bad habbit. You could even call it an anti-pattern. Why? Because for instance it would mean that when your client hangs up it would roll back your transaction. That is clearly unwanted in 99% of the cases.
As #mwhs commented, Apache Isis provides plenty of guidance on layering your app. To figure out whether it fits your requirements, you could run through this tutorial I presented at a recent conference.
I am developing web application with Java EE 6. In order to minimize calls to database will it be a good idea to have classes:
Data access class (DAO) will call only basic methods getAllClients, getAllProducts, getAllOrders, delete, update methods - CRUD methods.
Service class which will call CRUD methods but in addition filter methods e.g. findClientByName, findProuctByType, findProductByYear, findOrderFullyPaid/NotPaid etc... which will be based on basic DAO methods.
Thank you
In my experience (albeit, limited) DAO classes tend to have all the possible database operations which the application is allowed to perform. So in your case, it will have methods such as getAllClients() and getClientByName(String name), etc.
Getting all the users in your DAO and iterating all over them until you find the one you need will result in unneeded waste of computational time and memory consumption.
If you want to reduce the amount of times that your database is hit you could, maybe, implement some caching mechanism. An ORM framework such as Hibernate should be able to provide what you need as shown here.
EDIT:
As per your comment question, no, your service will not be made redundant. What one does is to usually use a Service layer to expose the DAO functionalities. This will, basically, not make the DAO visible from the from front end of your application. It usually also allows for extra methods, such as, for instance, public String getUserFormatted(String userName). This will make use of the getUserByName function offered by the DAO but provide some extra functionality.
The Service layer will also make itself useful should there be a change in specification and you now also need a web service to interface with your application. Having a service layer in between will allow the web service to query the DAO through the Service layer.
So basically, the DAO layer will still worry about the database stuff (CRUD Operations) while the service will adapt the data returned by the DAO without exposing the DAO.
It's hard to say without more information, but I think it's probably a good idea to leverage your database more than with just CRUD operations. Databases are good at searching, provided you configure them correctly, so IMHO it's a good idea to let your database handle the searching in your find methods for you. This means that your find methods would probably go in your DAOs...
It's good to think about/be aware of the implications of DB access on performance, but don't go overboard. Also, your approach implies that since your services are going to be doing the filtering, you are going to load a large amount of DB data into your application, which is a bad idea. The bottom line is you should use your RDBMS as it is intended to be used, and worry about performance due to over-access when you can show its a problem. I doubt you will run into that scenario.
I would say that you're better off having your DAO be more fine grained than you've specified.
I'd suggest putting findClientByName, findProuctByType, findProductByYear, findOrderFullyPaid/NotPaid on your DAO as well in some way because your database will most likely be better at filtering and sorting data than your in memory code.
Imagine you have 10 years of data and you call findProductsByYear on your service class and it then calls getAllProducts and then throws away 9 years of data in memory. You're far better off getting your database to only return you the year you are interested in.
Yes, this is the right way to do it.
The service will own the transactions. You should write these as POJOs; that way you can expose them as SOAO or REST web services, EJBs, or anything else that you want later on.