Spring layers confusion - java

I am new to Spring and Hibernate. I am actually facing problems defining the layers of my application which is to create a movie site where one can search movies,theaters,search movies by theater names and theaters by movie name.I summing up my queries as follows :-
What could be the entities in my application, I have created MovieEntity and TheaterEntity so far, how to proceed with the mappings between two.
My project structure should be something like this:
Entities, repositories and services. I am not sure where to fit my service layer, as all the methods I need to implement are defined in entities.
Thanks in advance .

There are many ways to do this, and therefore you will not find one definitive answer to your question. (I didn't downvote you, but I suspect that this is the reason for it.)
I would recommend looking at various open source projects (check github) and see how this is done by convention.
One popular way is to create DAO interfaces as a point of access to your data layer and create implementations of those DAOs that are specific to Hibernate. Your services would contain business logic and can use Spring autowiring to link to these interfaces. Your controllers shouldn't contain business logic and should really just route requests. Keep your validation code separate whenever possible too. Doing so makes it particularly easy to unit test.

Related

Mechanism/Technique for auditing API request/ interface methods

In my Web-API, i have various methods declared at interface level. And implementation of each method is written at service level. At each method declared i have added audit Annotations, something like this
CreateStackResponse createStack(#AuditId("id") String id, #AuditModule("module") String module, CreateStackRequest createStackRequest)
My Audit table columns are: id, context-id, message, details, user-id, module, submodule,...
How can i build a message(for eg. "create stack request is initiated by abc user") to store. One solution is like at service level i will call one method(say logEvent(required parameters)) which will store audit in database. Can we do this with simple Annotations, at interface level itself?
For example how can i save audit logs as shown in aws elastic beanstalk's event tab.
Annotations do not provide any behavior to your code all by themselves. All that annotations are is what their name implies...extra information attached to your code. The power of annotations comes in when you have code that uses introspection at runtime to look at your compiled code's definitions and do things based on these annotations.
The Spring framework does this extensively. It looks at the annotations on your code and uses them to decide how to wire up your application. It will often create wrapper classes around your own classes so that it can inject its own logic on top of your code.
You could certainly do something like this on your own, but it isn't trivial. I would suggest looking at AspectJ, or some other aspect oriented programming (AOP) framework. I would suggest studying the idea of aspect oriented programming in general, as what you are wanting to do is one of the most common problems that it looks to solve. Using the Spring framework would also be a great leg-up on attacking problems like this. It includes a module for doing AOP, "Spring AOP".
No matter how you go about this with annotations, you're talk about a lot of learning and potentially restructuring your code to use third party packages. You may very well want to give up the idea of using annotations and just put simple logging code in your primary logic.
I just Googled for "using aspect oriented programming for auditing" and got a lot of interesting hits. Here's one such hit. I don't know if it's the best resource for your purpose, but it will give you an idea of what I'm talking about here:
http://idanfridman.com/2014/05/13/clean-auditing-infrastructure-for-your-app-using-aop-custom-annotations-and-reflection/

Working with multiple services/controllers in spring

I'm working with spring in java and I'm trying to create a rest-API for my program. I have 3 entities to manage so I also have 3 DAO classes.
my problem is that I have 2 types of users (player and admin). every one of them has different operations he can do on each of the entities/tables.
My question is what is the best way to implement these requirements.
should I have 3 services and 3 controllers for (one for each of my entities/tables) or should I create 2 services and 2 controllers (one for each type of users) Or maybe there is a better way than what I suggested?
EDIT:
Another thing that may be important is that I need to verify the data in the service, the verification process checks for connections in tables so in each service, I will also need to have Dao objects for different entities (For Example checking if a new action has an element on which the action occurred.
It sounds like you are probably going to have different functionality for the different types of user. It's kind of the point that admins can do things that players can't do. So there are going to be separate admin-specific service methods, the controllers used by the players don't need to have admin services wired into them.
Also it's the nature of transactions that they usually are not specific to an entity, usually you have different entities you want to deal with in the same transaction. If so then having a different service for each entity probably doesn't make sense.
On the controller level, use Spring Security to enforce who can call what endpoint. I would organize the controller endpoints into classes depending on what shared enough things in common, but how you break it up is not a huge deal.
For services, I would have one service implementing logic for normal players, and one service implementing administrator functionality. If there is a lot of code for either of these then I would think about breaking it up into separate services, keeping the distinction between services containing methods for normal players vs. for admins.
You can look into method level security with Spring Security. Baeldung has quite a nice guide about that topic.
You basically annotate certain controller methods and then access to them is denied for users that do not fulfil the conditions of the annotation.
E. g. Thymeleaf offers integration with Spring Security too, so you can make buttons unavailable in your HTML when the user does not have a certain privilege

Java config for Hibernate/JPA?

As far as I know, there are two ways to configure JPA / Hibernate:
XML based configuration through something like hibernate.cfg.xml. I don't like his approach because, well, XML ...
Through annotations in the entity object. Much better than the XML config, but it couples my entities to JPA.
As I am currently investigating an architecture where the domain model does not know anything about the database (The 'Onion' architecture), I am looking for is a way to specify the mappings without changing my entities.
Of course I could create separate mapping classes, e.g. if I have a Customer domain object, create a JPA-annotated CustomerEntity and let the repository translate from one to another. But this approach doesn't feel quite right because the Customer and CustomerEntity will essentially be the same.
So it seems like I have to resort to Hibernate XML configuration, but as mentioned before, I don't like that approach.
Spring has a nice way of configuration: Java-based configuration. I was wondering if there is something similar for Hibernate/JPA configuration, and if not, why not?
My apologies if none of the above makes sense, but any help is welcome, even if it doesn't answer my question :-)
I've never heard of an Onion Theory of Java EE design. I did hear of The Onion, but that's a satirical newsletter (if that :-). Separation of concerns in Java EE I typically expressed as a MVC, or Model View Controller architecture. Your JSP or JSF pages will be your view, your #ManagedBean controllers will be your controllers, and your model will hold your Entities.
The model, which is where the JPA will be, can usually be further separated into a Service Layer, a Persistence Layer and EIS (Enterprise Information System) or Database tier. The Service tier will hold your EJBs, annotated with Stateless, Statefull or Singleton, and will encapsulate the business logic for the application. The Persistence Layer will have #Entity annotated objects that are stored by the Database.
Java EE defines these layers with JSR's, with numbers of some sort. For example, the Java Persistence API (JPA) is JSR-220. Tests are developed against these JSR's and if a vendor meets these tests then their product can be (More or less) swapped out for another vender's version.
Apparantly there is somethinig called Fluent NHibernate for C#, which does exactly what I was looking for.
Unfortunately, there seems to be no "Fluent Hibernate" for Java.
There is a fluent-hibernate project on GitHub, but that one seems to be about fluently writing HQL-queries, not about mapping configurations.

spring mvc dao and service bean mapping

I am new to Spring and hibernate.
I am trying to learn the best practices and design methodoligies in j2ee apps.
I have a managed to create a basic spring mvc web app. now lookin for that
- how should i map my service beans to dao beans or should just use dao beans only.
- Is there any need to make DAO classes singleton
- If i use same dao bean for the jsp, then e.g. onSubmit if I have to enter data on multiple tables (dao beans) then how would I do that.
1 service bean to more than 1 dao beans??
and any refrence material on designing good web app using spring hibernate would appreciated ;)
thanks
You must use service bean. service logic should be there only.
DAO should only for DB related operation.
Now you can inject multiple DAO in your service bean.
FWIW - I just went through a similar learning process on Spring. The good news is, there are a lot of examples out on google; the bad news is, there are not a lot of "complete" examples that are good for rookies (also if you are going to target v3 Spring, there is a lot of pre-v3 stuff out there that can be confusing based on the new baseline). What worked for me was the following: started with the sample applications on the SpringSource site (http://www.springsource.org/documentation). Between their handful of examples, there are just about all the pieces you will need, at least in minimal form. When I found something in those examples that I needed, I googled based on similar terms (some of the # annotations etc) to find more complete information/better examples on that given topic. Many of those searches led me back to this site, which is why I started frequenting here - lots of good questions already answered. I guess this isn't an overly insightful answer, but this process got me up and working through the basics in a fairly quick amount of time.
DAO layer and service layer are different entities:
DAO is responsible for getting and putting single objects from\to DB. For example, get User(id, name, lastname) from DB.
Service layer is responsible for your business logic. It can use several DAO objects for making one action. For example, send message from one user to another and save it in sent folder of first user and in inbox of recipient.
A service is about presenting a facade to the user that exposes business functions that the user can take. Basically, if you have a set of low-level use cases, the methods on the service would line up with individual user actions. Services are transactional, generally if the user does something we want all the consequences of that action to be committed together. The separation between controller and service means we have one place to put webapp-specific functionality, like getting request parameters, doing validation, and choosing where to forward or redirect to, and a separate place to put the business logic, stuff that doesn't depend on webapp apis and is about what objects get updated with what values and get persisted using which data access objects.
I see a lot of cases where people seem to think they need one service for each dao. I think their assumption is that because Data Access Objects and Controllers and Models are fairly mechanical about how they're defined, services must be the same way, and they construct them with no regard for the use cases that are being implemented. What happens is, in addition to having a lot of useless service boilerplate code, all the business logic ends up in the controller jumbled up with the web-specific code, and the controllers become big and unmanageable. If your application is very simple you can get by with this for a while, but it is disorganized, it's hard to test, and it's generally a bad idea. Separation of concerns, keeping infrastructure code in one place and business code in another, is what we should be aiming for, and using services properly is very helpful in getting there.

Seam application Architecture

I need to implement quite big system in Seam. I'm considering the way of designing the architecture. If it's good to use page controllers or application controllers or front controller or every each of them. If it's helpful to use backend bean or maybe there's no need to do that. If you have any suggestion or link to helpful article I will appreciate it.
Thanks a lot!
Daniel Mikucki
If you need to learn a lot about Seam for a project, I recommend you get the Seam In Action book, which is the best on the subject.
To answer your question, personally I prefer to use the pull-MVC style in Seam, where you refer to data in your view templates that Seam takes care of initialising, as needed, using #Factory methods. However, there is more than one way to do it in Seam, so it is worth reading about the alternatives first, hence the book recommendation.
Alternatively, build a few Seam applications first to throw away before you try to build one 'right' :)
Daniel,
It is good practice to use a front controller, most people aren't aware of that design pattern.
It is a really good design pattern to use because it ensures you are accessing the application through a single entry point. You can monitor everything that comes and goes easily with less configuration. You reduce the amount of possible code duplication because there is a single entry point. In addition to having less code to maintain, the code should be easier to follow since there is only one way in. You can then easily follow the execution flow of the application.
Unfortunately for Seam, there isn't really a front controller pattern. I haven't spent as much time as I would like to develop my own, but security and audit-ability are my number one focus.
As far as page / application controllers go, in Seam, you have more contexts or scopes available. Event, Page, Conversation, Session, Application, to name most of them.
If you're developing a controller or in Seam, a page action, most of the time, it will be event based. That is the shortest lived scope. If you have page flows, you would then use conversational-scoped components.
Take a look at the examples in the source code. You can do a lot with very little code, it is amazing, but at the same time, there is a lot going on that may take a while to pick up on.
The n-tier design that most places follow doesn't necessarily apply here. For most of my pages, I define a query that I'll use in XML (entity query), then I'll inject it into my page action and call it there. So instead of having a controller, service, dao, and entity classes, you end up with simply a page action, the queries, and entity classes. You can cut out the service and dao layers in most cases.
Your whole definition of a service might change too. For me, a service is a service provider such as notification, security (auditing), exception handling, etc. all of these services run in the background and are not tied to a particular http request.
Walter
Daniel,
I have used one controller per page, one service and one dao per entity.
Use case logic goes in the controller
Entity specific business logic goes in entity service.
Actions which span multiple entities you can create a facade service - something which sits between controller and entity services
While the above is a good and practical approach, ideally:
you could break out any non MVC code from controller into its own service class, ie. 1 service class per page
you should only access the entity dao via the entity service.
Here's how the control would flow:
Ideally:
UI
-> PageController.java
-> PageService.java
-> EntityService.java
-> EntityDao.java
Practically, you could trim down a few layers:
UI -> PageController.java -> EntityService.java
Or for actions touching multiple entities:
UI -> PageController.java -> Facade.java -> Entity1Service.java,Entity2Service.java
PageController.java would be a Seam #Component and in your ui you can refer it as:
#{pageController} and pull the data from the view.
In architecture, the most important thing is how you layer things in the stack is avoid circular dependencies between layers. For example, Entity Service should not reference Controller and so on.
The other important thing is to be consistent about layering in the entire application. Use code generators if you can to keep your code consistent across the application, it really pays off for large projects. Look into Clickframes if you are interested in code generation (Clickframes generates starter code for Seam apps with full JPA/valdiation/security support which you can then modify). See this Seam demo build with Clickframes if interested.

Categories

Resources