Using POJO as Model in JSF and JPA project, is that right? - java

i'm developing a project using JSF 2 and JPA 2 (EclipseLink 2.3).
In JSF 2 I learned that we must separate the Model from Controller and the same thing to the View (thanks BalusC).
But now with the POJO's generated from JPA, I wonder if the bean, the model, it should be the pojos now.
My view is gonna be my .xhtml pages, developed in JSF 2.0, that will interact with my controllers then in controllers call the DAO's classes and then operate in my database.
Is this right ? I mean in the concept of MVC ?
I want to do everything right, any tip ?
Thanks in advance.

"MVC" has in JSF multiple points of view. From the high level view, the Model is represented by EJB/JPA and eventually DAO/DTO (if any). The View is represented by your own JSF code (which consits of managed beans and Facelets templates). The Controller is represented by the FacesServlet.
From low level view (a further subdivision of the high level View), the Model is represented by entities or DTOs. The View is represented by your Facelets templates. The Controller is represented by your managed bean. It's basically a M(MVC)C.
Note that "POJO" is a rather legacy term from the old J2EE/Hibernate times. Nowadays, with Java EE/JPA, they're called "Entities". Yes, it are those #Entity Javabeans. Als note that some may opt to use plain vanilla DTOs instead of entities which should decouple your JSF code from the service layer. JSF should then use those DTOs as model and the service layer should in turn map between those DTOs and the real entities. This is in my opinion not necessary. EJB3/JPA2 is a pretty slick API which already minimizes a lot of boilerplate code for which you would have used DAOs/DTOs like as in old J2EE ages. With Java EE 6 and higher, there's not really a need to be able to switch of service layer to for example Spring. Everything is already well thought out and standardized.
See also:
What components are MVC in JSF MVC framework?
Difference between DTO, VO, POJO, JavaBeans?
I found JPA, or alike, don't encourage DAO pattern

Not completely right. It's usally better to avoid referencing model objects directly in the view; you can substitute them with DTO(data transfer object) that just serve the purpose of containing the data to be displayed

Well, in my opinion, this is not correct.
The XHTML pages is the view, but the controller is the JSF servlet (already provided by the framework) and what you call "controller" is actually the model (the business logic). The JPA POJOS are part of the model (the data model).
From the View you should invoke the business logic to obtain the result (as JPA Pojos) and use directly them (no transformation to DTO needed in your architecture) in the view.
Inside your model, you can organice the business logic as you whish (if you think that you need a DAO layer, very common in the industry, you can just put it).

Related

MVC Structure for Web application in Spring?

Using Spring MVC to develop a web application. Earlier I was using Controller layer, Service layer(business logic), Model layer(entity) and DAO(DB) layer.
But someone pointed out that i should introduce two more layer ie. dto layer for collecting data from front end and transforming layer which will convert than dto into model(entity) layer objects.
Now I am using:
Controller layer (which will send the data to DTO layer)
DTO layer (which will send the its data to transforming layer)
Transforming layer(for converting dto layer objects into entity layer objects)
Service layer(Business logic)
Entity layer(POJO which will map with database)
DAO(which will use entity objects to store the database)
In this way we can keep front end and backend data different. Please help me out, is this a proper structure for Spring MVC ?
There is an interesting question answer thread on MVC here:https://softwareengineering.stackexchange.com/questions/127624/what-is-mvc-really
Some of the key points to remember when designing an application should be; layered and loosely coupled.
In your scenario, having additional transform layer does not necessarily make our break MVC pattern. It is just an additional layer you have introduced in MVC; a design strategy followed by many.
DTO is just a pattern to encapsulate data. Normally is used to be returned in your controllers, but you don't need always to create a DTO, you can use your entities for this. I just use a Dto when i need a different data structure, that any entity support, like a report for example.
About your project layers Model/Dao/Service/Controller it's correct, i strongly recommend for you the book Domain-driven design, it's will help you to build your software architectures!
But someone pointed out that i should introduce two more layer ie. dto layer for collecting data from front end and transforming layer which will convert than dto into model(entity) layer objects.
No, it's incorrect. You should use only layers that are necessary.
Earlier I was using Controller layer, Service layer(business logic), Model layer(entity) and DAO(DB) layer.
This is also incorrect. There's no strict definition of MVC is a pattern, but it's used only on one layer called a view layer, or in other terms presentation layer. Where the model, view, and controller reside. There's another layer called a service layer, which is optional. Then persistence layer, in this layer you model your objects and save them in the database or somewhere else. No more layers are necessary to the simple web application.
A few words about model, it's a set of classes that you want to persist or use in the view layer to show/store the data. Here you can play with it, because someone prefer to use it's own model to show/store the data, and others prefer their own model to persist it. These transformations are usually done in persistence or service, or in both layers. Keep in mind that all layers a loosely coupled to each other, but you can transfer data beans from one layer to another and back without problems. Entities in the detached state or other beans like DTOs are examples of such objects that you can pass and bake between layers. And no additional layers are necessary.

Do you write Hibernate code inside POJOs?

We have a web application which uses JSP, Servlet and Hibernate. The design pattern we got is MVC like, which means,
JSP -> Servlet -> Beans (POJO)
Now the question. Once of out developers has inserted the hibernate queries, hibernate session creation etc inside POJOs. Now inside these POJOs, there are methods like getAllEmployees(), getAllAgents() etc. This made it extremely hard for us to change the database tables (we handle database manually, using MySQL Workbench) and use automatic tools to re-generate the POJOs because these methods will be lost.
Now there are 2 arguments. One is that this maintaining hibernate queries, sessions inside POJOs is a good work, because it seems like pure MVC. The other argument is move the hibernatre code to Servlets and call the POJOs just like beans, only to set and get values.
We have not worked in Hibernate before. From above 2, what is the preferred place to write hibermnate code when it comes to hibernate?
Finally, please note we are not interested in Spring or other frameworks, we use pure JSP and Servlet with Hibernate
Probably, what you need is another layer of abstraction. Since your pojos are recreated after new migrations, you shouldn't insert code in it (I don't agree with that aproach, but that's just my opinion :-) )
JSP -> Servlet -> NewLayer -> POJO
I don't know where you put your business rules, but in this scenario it will be in the "NewLayer" wich would consist of a "hibrid" layer of service and dao.
I would recommend these readings to rethink your actual architecture:
https://softwareengineering.stackexchange.com/questions/220909/service-layer-vs-dao-why-both
Responsibilities and use of Service and DAO Layers

Where should be placed business logic in the three-layer system?

I know there are many questions about my problem and I've read a lot, but I'm still feeling little bit stupid, because I still haven't got it. So I'm trying it on my particular problem.
I'm implementing the school work. It should be a part of the information system, which has to be layered. We have to write it in Java or C# (I've chosen Java). We have to use two different data sources and two different views, in my case, oracle db and xml as data source and Java Swing and JSF as views.
According to the book "Patterns of Enterprise Application Architecture by Martin Fowler" there are three principal layers:
Data source layer: I've generated entities using Hibernate ORM, I've created data access objects to implement simplier "interfaces" to getting the data.
Domain layer: ...
Presentation layer: I've created the Swing GUI and some .xhtml pages with MVC logic
If there wouldn't be any "calculations" in the system, but only simple achieving and returning data, I'm done, everything is ok. But I'm, for example, implementing the system, which should manage the competitions of the sport dancing, and during the competition I need to generate sets of couples for every round, after the competition I need to calculate points of every dancer, increment points if necessary and so on.
I know, that it is the responsibility of the Domain layer (business logic), but where in my code with? What names for these objects should I choose and where to put them in my code structure?
My structure:
hibernate.cfg.xml (configuration of hibernate)
hibernate.reveng.xml (reverse engineering file of hibernate)
isets.dao (package)
isets.dao.hibernate (package)
HbmCompetitionDao.java (data access object of Competition entity)
...
isets.dao.xml (package)
... (data access objects of another entities, which are stored as XML)
isets.entities (package)
Competition.hbm.xml (generated entities)
Competition.java
...
isets.util (package)
HibernateUtil.java (file to get session factory object)
Where should I put my business logic and what should be the names of these classes?
Thank you very much for your help. Bye :-)
Usually domain layer means "entities" (models for domain) and domain services.
Entities hold all business logic related to them. Validations (checking that they're in correct state) and calculations are usually put in the property setters/getters, while operations for transforming data are exposed via public methods.
Domain services are classes that operate with multiple entities and do some calculations and/or transformations between entities.
A few things to consider. In order for this design to work properly (so it is testable, decoupled etc), dependency injection (DI) must be used. Domain should never be bothered by getting or saving data etc. It should be clearly decoupled and all its dependencies should be known upfront.
If it is a simple application it may be wise to combine domain layer and data access layer, so objects that are created from ORM are already entities. Just add domain services (if you need them). Use then the same entities on presentation as well (as model for MVC). This will decrease the need for mappers to map between ORM made objects (lets call them dbos), entities and possible models needed for presentation. Of-course if you need different objects for each layer, by all means create them. Just don't over complicate if it is not needed.
One of the possibilities is to structure you application as follows:
1) #Entity annotated POJO represent your data layer representing tables, relationships between them, etc using JPA
2) Stateless session beans implementing Session Facade desing pattern wrap your container managed CRUD operations. There are typically one facade per entity, they usually look like this:
#Stateless
public class FooFacade extends AbstractFacade<Foo>{
#PersistenceContext
EntityManager em;
public EntityManager getEM() {
return em;
}
public void save (Foo entity) {
getEM.persiste(Foo.class, entity);
}
public void reload (Foo entity) {
getEM.refresh(entity);
}
//other similar stuff
}
AbstractFacade is an abstract class that provides genetic find and other operations that look identical in all facade classes (to avoid duplicate code). This e-commerce sample application can be used as a great example of this strategy. The classes are usually named as EntityName + Facade.
3) Stateless session beans that realise your business logic (calculations for competitions in your case or adding goods into basket, implementing checkout, etc. for ecommerce app). Usually they talk to data layer via *Facade EJBs mentioned in part 2 above. This part of the aforementioned tutorial realises these EJBs.
4) Servlets to which your UI layer will refer their request. Servlets will utilize EJBs from part 3 to serve the requests.
5) UI layer - JavaFX, Swing, JSF, JSP, Apache Wicket framework - add anything you like.
Such a structure gives you both flexibility and scalability. Centring your business logic in stateless beans means you can scale well because they are pooled and every instance in the pool can equally be used when you application (e.g. servlet) needs talk to an instance of such a bean.
I strongly recommend you to thoroghly read through the ecommerce tutorial on Netbean's website to see the concrete implementation of this scheme. Here is the download link for the source code of the application, AffableBean ecommerce system, built through the tutorial.

Doubts about MVC Model

I've been told that MVC is an architecture pattern for the presentation tier on a multi-tier architecture. I didn't understand the MVC Model concept.
So I made a web application, as an aproach to learn MVC model, only using JSP and Servlets, I made the DataAccess layer too.
In my WebContent folder, I put all the views.
In my src (Java content) folder, I made 4 packages.
data
presentation.model
presentation.controller
businessEntities
I used Servlets as Controllers (used the FrontController pattern) and JSP for all the Views.
As the title says, my problem is with the model.
Now, lets make an example..
I have 2 classes.
- Car
- CarLogic
CarLogic is a class that calls a possible CarDAO to get data and to return it to anyone who asks it. Car is just the POJO.
I placed CarLogic inside presentation.model and Car on businessEntities.
Am i wrong? What should i put on Model package?
Thanks!
When nested in the presentation layer of a multi-tier architecture, MVC's models are usually nothing more than (possibly enhanced) key-value maps.
The controller, after having called the appropriate business layer service, instanciate a new map with the values the view will have to display.
Spring MVC for example implemented the MVC pattern this way: see how the ModelMap extends LinkedHashMap.
See this answer to see a typical HTTP request life cycle, when the MVC pattern is nested in the presentation layer of a 3-tier architecture.
So to sum up, I would put CarLogic in your businessEntities package, and the Car POJO
within a new presentation.bean package for example (so you won't need your presentation.model package anymore). Thus, your controller would add the Car instance as an attribute of the request, which would then play the part of the model:
request.setAttribute("theBean", yourBeanInstance);
In your JSP views, simply use ${theBean.anyProperty} to access the attribute (don't forget the getter in your bean). Note that the EL will scan the following scopes in given order: page, request, session, application; the first found match will then be returned.
Model View Controller in and of itself is a pretty simple pattern.
From the wikipedia artical:
A controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document).
A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands. In some cases an MVC implementation might instead be "passive," so that other components must poll the model for updates rather than being notified.
A view requests information from the model that it needs for generating an output representation to the user
At least it was simple pre-web and pre-SOA.
The view part is still pretty straight forward, it simply presents the model.
Controller-wise, the web, in its traditional http/html sense rather than the newer JavaScript/AJAX/websocket sense, has made the controllers iteraction with the view much more visible than it was in say a Swing application. This means in addition to their traditional role, controllers in a web-app are likely to not only interact with the model but also have some knowledge of the views.
Model-wise, pre-SOA the model represented both the data and the behaviour of the business. More recently anemic domain models have become popular with behaviour implemented in separate classes from the representation of the data, which is passed to the logic classes (services).
It's this point, relating to the separation of data and logic that I believe your question relates to. Personally, for simple systems, I prefer a rich model with the data and behaviour in the same classes, hence the packaging is simple. However I appreciate that sometimes the benefits in separating the logic from the data and in such cases I'd create a separate package (and probably a separate jar) to contain that logic.
The word "model" means subtly different things in the term "model-view-controller", and when you say "model layer" in an n-tier architecture such as yours. From the point of view of MVC, everything the controller passes input to, and fetches viewable data from, is the "model".
This includes your domain model (Car), and business logic (CarLogic). You don't need to necessarily structure your application to exactly match the pattern you're using on the UI side. (In fact, the MVC pattern is probably insufficient to cover an entire application to begin with.)
So in your case, putting Car into businessEntities is fine. Not sure about having presentation.model to begin with – business logic isn't a presentation concern, and probably belongs in a layer on its own. Which is where I'd put CarLogic.
I have no idea what the data package is supposed to be at all.
This split means there doesn't seem to be a dedicated presentation model in your application. This might or might not be an issue. In a web application, what the presentation model usually does is encapsulate user input, or maps the business entities to a structure that fits the needs of the view better – flattening complex relationships etc. (In classical Spring MVC, these would be the Command and Model classes.) In a simple enough application, or using an advanced enough web framework, it's possible to directly use domain model entities in your views.
As an example of what a distinct presentation model would do, consider the internal system a school would use. You'd have a bunch of students, and some classes they can enroll in. At the business entity layer, you'd probably have a separate Enrollment entity that would hold attributes like date of enrollment, references to the grades a student got in the class, etc. However, when a view in the application needs to display the list of classes a student is enrolled in, it doesn't really need to see the Enrollment object at all. Thus it makes sense to have a presentation model object Student that only has a list of Class objects in it. (And the requisite code that reads the business entities and maps them correctly to this structure.)
From Wikipedia about MVC:
Model–view–controller (MVC) is a software pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user. The central component, the model, consists of application data, business rules, logic, and functions. A view can be any output representation of information, such as a chart or a diagram. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants. The third part, the controller, accepts input and converts it to commands for the model or view.
I highlighted one sentence, that usually is not understood. The model is a really rich model. That means, it also contains every logic that works with the data. It is up to you, whether to have separate classes for data and for logic (which reduces the data classes to structs or records), or whether to have richer data classes that already contain some business methods (the way that I prefer).
That said, the controller is just the interaction between the model and the view. In Swing applications - for example - the controller is nothing else than the various listeners (an ActionListener, for example).
So, to answer your question: Having a separate data access layer is a good thing. This is where your DAO class belongs to. The data and logic classes (the model) belongs to the model package. I would not create several packages for them.
MVC is a common design pattern used by many modern web frameworks, f.e. GRAILS, Spring MVC or ASP.NET MVC. You see the MVC pattern is included in their names ;)
For the MVC-pattern you actually need three packages:
model
controller
view
In the model package you put your classes which will be used to hold your data. The controller classes contains the logic to controll which view is called and which data should be used in those views. The views itselfs contains the information how to display your data on the screen. There shouldn't be any great logic, f.e. just JavaScript. The business logic should contained in a separate package. If you need this logic, you can call is from your controller.
Your packages are (I hope i read them correctly!):
data
presentation.model
presentation.controller
businessEntities
According to the MVC-pattern is suggest the following usage of your packages:
"data" or "model" - use this for your Car class
"controller" - use this for your controller logic
"presentation" or "views" - use this for your views to display your data on the screen
"businessLogic" - use this for your CarLogic class
MVC stands for Model View Controller.
Model is where you store entity objects
View you store Presentation objects
Controller is where you map your attributes that are present in the Model to the widgets.
so that the attributes are set to the entity objects from the widgets input.

Simple but good pattern for EJB

What would you suggest as a good and practical but simple pattern for a solution with:
HTML + JSP (as a view/presentation)
Servlets (controller, request, session-handling)
EJB (persistence, businesslogic)
MySQL DB
And is it necessary to use an own layer of DAO for persistence? I use JPA to persist objects to my DB.
Should I withdraw business logic from my EJB? All online sources tell me different things and confuses me...
I would definitely put the business logic in Stateless Session Beans. Stateless session beans are nice as they nicely capture the transaction boundaries. And it decouples the View layer from the persistence layer.
Take care that the methods of the SSB correspond to small business goals the user wants to achieve.
Another point is that you must be sure that the data you return has all data in the object tree and that you do not rely on lazy loading to get the rest, because this causes all kind of problems.
Stay as far away as possible from Stateful Session Beans : they are bad news and are a broken concept in the context of a web application.
For long running things, consider using Message Driven Beans which you trigger by sending a JMS message. These are a nice way to do background processing which frees the business logic faster, keeps transactions shorter and returns control to the end user faster.
What would you suggest as a good and practical but simple pattern for a solution with JSP/Servlets + EJB + MySQL
Use the MVC framework of your choice, Stateless Session Beans for the business logic and transaction management (prefer local interfaces if you don't need remoting), Entities for persistence.
Inject your EJBs wherever possible (if you are using Java EE 6, this means anywhere and you can also skip the interface).
And is it necessary to use an own layer of DAO for persistence? I use JPA to persist objects to my DB.
Some might say yes, I say no in most cases. The EntityManager already implements the Domain Store pattern, there is no need to shield it behind a DAO for simple needs.
You might want to read the following resources for more opinions on this:
Has JPA Killed the DAO?,
JPA/EJB3 killed the DAO,
and the more recent DAOs Aren't Dead - But They Either Collapsed Or Disappeared
Should I withdraw business logic from my EJB?
I wouldn't. Put your business logic in your (Stateless) Session Beans. EJB3 are POJOs, they are easily testable, there is no need to delegate the business logic to another layer.
Anno 2012 I would not recommend going for Servlets and JSP as the presentation layer. This was all the rage in 2002, but that's a decade ago.
Today Java EE has an excellent MVC framework build in called JSF. You are much better off using this instead. You most likely want to fetch some Widgets from the component library PrimeFaces, as all the standard ones are a bit basic. A utility library like OmniFaces is a great addition as well.
Regarding the DAOs; don't go as far as directly using the entity manager in (JSF) backing beans, but if you are already using Service classes (transactional boundaries) for your business logic , using a DAO as well might be overkill.
There are still some small advantages of a DAO, like a dao.findByName(...) looks a little clearer than loading a named query, setting a parameter, and getting a (single) result, but the cost is that you have to maintain a seperate DAO for each Entity, probably in addition to some Service.

Categories