r/javahelp • u/_SuperStraight • Jun 28 '24
Understanding MVC architecture
I'm reading about MVC architecture, and what I understood are:
Modelessentially are the metadata of a table, and its instance, bottom line, is a tuple of that table.Serviceis responsible for CRUD+retrieval of data from the table and transform it into Model instance.
What I want to ask is, should there be one more class which sits between services and database, exclusively converting the requests from Service to SQL queries, and returning a ResultSet to the Service (this class will exclusively connect to the database), or should each Service run their own SQL queries (Every service can connect to the database)?
My understanding could be wrong so corrections and guidances are most welcome.
Edit: my scope of this architecture is just Java and a JDBC; no Spring, JPA or any other frameworks are involved.
2
u/Beginning-Ladder6224 Extreme Brewer:snoo_biblethump: Jun 28 '24
Always trust MSDN to teach you these things. I understand you need to have Java, but MSDN is a fantastic resource.
And MDN. Mozilla. They do amazing job.
https://developer.mozilla.org/en-US/docs/Glossary/MVC
And then there is wikipedia.
2
1
u/Significant_Newt8697 Jun 28 '24
just have one dao for every table that you have in the database. In spring, the dao is already provided if you use the jpa specification
4
u/wildjokers Jun 28 '24
just have one dao for every table that you have in the database.
I disagree. That gets you going down the path of badly performing database queries because it gets you thinking about how to query individual tables, rather than querying in the aggregate for all the data you need to fulfill a request with as few round tips to the database as possible.
4
u/Significant_Newt8697 Jun 28 '24
you are talking about joins, I never said that explicitly, but for joins you can always make an exception. Having one dao for each table makes it easy to scale that layer since it's independent
1
1
u/wildjokers Jun 28 '24
Having one dao for each table makes it easy to scale that layer since it's independent
No, no, no. Always think about how to get all the data you need for a specific business operation with as few round trips to the database as possible. If you start having a DAO for every table you are going to start doing things like querying for a users, then all their orders, then all their user contacts, etc. rather than just doing a couple of joins and returning all of that information at once.
1
u/Significant_Newt8697 Jun 28 '24
yeah, I said you can make that exception. But when designing, you should start with the assumption that all tables need to have a dao then from their you can decide what daos not to have since they are already covered by the daos of other tables (this is in case of relations)
0
u/_SuperStraight Jun 28 '24
Ok so what I called a Service is actually called DAO.
So what you're basically saying is to have each DAO execute its own SQL command for whatever operation is called, right?
3
u/Significant_Newt8697 Jun 28 '24
no, the service layer is different from the dao. Basically, you have the controller, then service, then dao. So inject the dao into the service, but have a different dao for every table that you have in the db.
1
u/_SuperStraight Jun 28 '24
Ok alright. Thanks for the clarification.
Which one of them (DAO/Service) will be basically querying the Database?
2
u/wildjokers Jun 28 '24
Please note you don't want a DAO for every database table. That part is bad advice. You need to think about querying your data in the aggregate i.e. how to get the data you need to fulfill a request with as few round-trips to the database as possible. You also only want to return the columns you actually need.
0
u/_SuperStraight Jun 28 '24
But DAOs only have either
getAllorgetByIdmethods, then how can we specify conditions to select only specific columns, and how to use the WHERE clause in DAO?3
u/wildjokers Jun 28 '24 edited Jun 28 '24
But DAOs only have either getAll or getById methods
That isn't true. Think about your queries in the aggregate and not individual tables. You can get away with thinking about individual tables for small little demo apps, but in a real application you need to query your database wisely. Which means getting all the data you need to fulfill a request with as few round tips to the database as possible (preferably one, but not always possible).
If you are just talking about a DAO that usually means raw SQL and you can write whatever SQL you want returning whatever columns you want. So you can add where clauses and joins like you would in any SQL statement. If a query joins a few tables together sometimes it is just a judgement call which DAO it should go into and there isn't necessarily a right or wrong decision. Also, rather than naming your DAOs after a specific table you can name them after a specific business operation if that makes more sense for your app.
If you pile more abstractions on top of your data layer like JPA/Hibernate and Spring Data JPA then there are abstractions available in those libraries that let you write custom queries.
1
u/_SuperStraight Jun 28 '24
So the gist is to have your custom SQL queries hardwired in DAOs of your liking, make them into a method and call whenever required.
1
1
u/Significant_Newt8697 Jun 28 '24
DAO stands for data access object, so it's the one that will have the queries. The service will call the dao whenever it needs data from the db, the service can also call other services for data, they need not be stored in the database.
0
u/_SuperStraight Jun 28 '24
service can also call other services for data
That's something I didn't pay any attention to till now. A service can call other services, (possibly for
JOINoperations), then return the final result to the layer above. Correct?2
u/Significant_Newt8697 Jun 28 '24
nope. You can think of the dao as a service that hits the db directly for data. The point is that data need not be stored in the db, it could be anywhere, for example it could be in a csv or an excel sheet, so you'd have a service that gets that data then your service can call that service
1
u/_SuperStraight Jun 28 '24
Thanks for the help.
As you said, A service can call other services as well, then suppose we are connected to a database having 3 different tables in it.
Service1 gets data as model1 from tab1, Service2 gets data as model2 from tab2, Service3 gets data as model3 from tab3.
So now if I want a Left joined result of tab1 tab2 and tab3 in all combinations possible for 3 tables (I think 4), then do I have to write 4 different methods to get these 4 different outputs? Or is there a trick in Service layer which addresses this problem?
2
u/Significant_Newt8697 Jun 28 '24
not what I mean. Have 3 daos for the three tables. If the tables have relations then you can make an exception and query from one table. Have one service also if the tables are related, then inject the daos into the service. For example, if you want to get top 10 students in a class and have two tables, one for student info, and one for their grades then you can just have one service and one dao since the data is related. In the dao, you write and execute the query that get's you exactly what you need. Ps., the pattern is having one dao for each table, but at times you can make an exception depending on your use case.
0
u/_SuperStraight Jun 28 '24
Or create a separate service with student info and grades DAOs injected?
→ More replies (0)
1
u/sedj601 Jul 02 '24 edited Jul 02 '24
Here is my unpopular opinion. These architectures can be very good. What I did was find a good one that works well for JavaFX because that's what I use the most. I also use C# and Django. Those have totally different architectures. Find one that you think is good for the language you plan to use and use it. Don't get caught up in the jargon. You will find that these architectures are not in stone and people can't seem to agree on what is what. It's just one big headache. Avoid asking about it because it will only lead to a very big rabbit hole. If you plan on using JavaFX, I would suggest following the following: https://stackoverflow.com/questions/32342864/applying-mvc-with-javafx. Do not attempt to call it MVC as stated because they will lead you down a rabbit hole. Just learn it and use it.
1
u/_SuperStraight Jul 03 '24
The link you mentioned has a post with link to MVC architecture in Java to Edencoding[dot]com website, but that article seems incomplete.
1
u/sedj601 Jul 03 '24
I don't use that link. I used the answer associated with the link I shared and the link to the full Github code to learn.
1
u/nator419 Senior Software Engineer and Team Lead Jul 04 '24
It is the Controller Service Repository model you want to look into. Controller is the class that contains your endpoints and handles requests which then calls the correct service. Service then does whatever may need to before calling on the Repository. The Repository interacts with the database.
1
u/_SuperStraight Jul 04 '24
Does the Entity Model (Student, Employee, Vehicle, etc.) exist in this model?
1
u/nator419 Senior Software Engineer and Team Lead Jul 06 '24
Yes, Entities typically refer to the data classes we use for the data we retrieve from a database or when passing data around.
1
u/wildjokers Jun 28 '24
In MVC the Model includes all your business logic, database access, and any validation. So the model includes all of your services and any DAO used to query data.
If you use JPA/Hibernate and then use Spring Data JPA on top of that then DAO's are called Repositories. So if you see someone using the term Repository that is analogous to a DAO.
1
u/South_Dig_9172 Jun 28 '24
Yes there is, MVC stands for (Model View Controller) but it doesn't mean that that's the only things you have. Usually with JPA, you have a repository class (think of it as a bunch of SQL commands) that you can use in your service class. Now since you are only doing JDBC, (I have no experience with JDBC, but I should), I agree with what you're saying where there could be one more class in between the Service and Database, where the service can call on this service to interact with the database. Basically a Data Access Object.
0
u/djnattyp Jun 28 '24 edited Jun 28 '24
Services should be concerned with the "business rules" of the application. DAOs or "Repositories" are what usually encapsulates the "interacting with the actual persistance layer" portion of the code - and each query usually doesn't return a raw ResultSet out to the caller - the DAO usually either also provides mapping logic or uses other "Mapper" classes to encapsulate mapping the SQL results to a model class or collection of model classes.
1
u/wildjokers Jun 28 '24
In MVC architecture DAO/Repositories are part of the model (as are the services). The model is simply all the business logic of the application.
0
u/_SuperStraight Jun 28 '24
Thanks for the clarification.
What else can be expected from a query if
ResultSetis not always returned? (Besides SQLException)?If DAOs are responsible for mapping the result to a Model or return error, what exactly are the "business rules" that Services are concerned with? Can I not just pass the DAO to the caller?
2
u/djnattyp Jun 28 '24 edited Jun 28 '24
The JDBC call returns a
ResultSetor throws aSQLExceptionthe DAO class encapsulates all of this so the caller doesn't have to worry about JDBC/database stuff. Plus, there are details like: you want to reliably close JDBCConnection,Statement,ResultSet, etc. classes or they can hang around leaking resources and using up DB connections. You don't want to rely on every caller to remember to do this.// model class public class Book {...} // DAO public class BookDao { public List<Book> list() { try (Connection connection = //However you get connections) { try (Statement statement = connection.createStatement()) { String sql = "select * from my_db.books"; try (ResultSet resultSet = statement.executeQuery(sql)) { List<Book> results = new ArrayList<>(); while(resultSet.next()) { results.add(mapBook(resultSet)); } return results; } } } } public Book get(int id) { try (Connection connection = //However you get connections) { String sql = "select * from my_db.books where id = ?" try (PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, id); try (ResultSet resultSet = statement.executeQuery()) { if(resultSet.next()) { return mapBook(resultSet); } else { throw BookNotFoundException("No book found for id " + id); } } } } } // mapping method inside the DAO // this could also be extracted out into a "Mapper" class if you wanted private Book mapBook(ResultSet resultSet) { return new Book( resultSet.getInt("id"), resultSet.getString("title"), resultSet.getString("author"), // etc.); } }"Business Rules" are whatever your application does that isn't covered by mapping requests/responses to from HTTP/JSON or whatever form your UI takes (Controllers cover this), or mapping to/from the persistence format (DAOs cover this). If you're just doing CRUD without anything else really it's your choice - you can just skip the "service" and call the DAO directly from the controller, or have a pass through method in your service.
1
u/_SuperStraight Jun 28 '24
Thanks for the detailed answer. This code cleared lots of concepts for me.
•
u/AutoModerator Jun 28 '24
Please ensure that:
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
You include any and all error messages in full
You ask clear questions
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.