Stateful session bean passivation with non-serializable EntityManager? - ejb-3.0

I have just read Why stateful and local anti-facades are KISS by Adam Bien where he suggests using a SFSB with an EntityManager to keep entities attached during the whole client interaction.
Does't this fail not in a clustered environment as mentioned in a comment but also whenever the SFSB should be passivated by the container?
If I'm right what kind of solution would you suggest? I thought to minimize the number of layers in the application it would be useful to bind the SFSBs to conversation scope and then reference them directly in my JSF views.

In general, having a stateful based architecture is counter scalable.
I have been working with EJB 3 SLSBs for over 5 years now in multiple projects and never had a real issue with merging entities.
If you want to you can decouple your client layer from your persistence layer by adding a layer of DTOs. This way you can design your entity model according to what's best for the business/persistence layer and your DTOs according to the way your client wants to present the data.
If you want to use the same objects you can still do that, you should only pay attention to which objects are "in the session" and which are detached, and you won't have any merge issues.

Related

MVC / Repository Pattern - Architecture

I have a project in which I am using NHibernate and ASP.Net MVC. The application is intended to allow users to track certain data and then produce views of statistics based upon the data entered. The structure of my application thus far looks something like this:
NHibernate Layer: Contains Repository<T> and UnitOfWork classes, as well as entity mapping definitions.
Core/Service Layer: Contains generic EntityService class. At the moment, this simply defines transaction scope via IUnitOfWork and interfaces with IRepository to provide higher-level data access services.
Presentation Layer (MVC Application): Not yet implemented, but contains the usual stuff plus dependency injection.
I have a couple of questions:
Is it poor design to allow my MVC application to handle dependency injection for ALL layers? For example, as well as dependency injection of EntityService instances into controllers, it will handle the dependency injection of IRepository into the EntityService classes. Should the service layer handle this itself, even though this would mean performing dependency injection in two distinct places?
Where should I produce my statistics? This business logic doesn't seem to belong in my service layer, which, at present, only contains entity type definitions and an interface for modifying and accessing entity properties. I have a few thoughts on this, but I'm not sure which I like best:
Keep my service layer as is and create a separate Statistics project - this is completely independent of the entity types for which it will be used, meaning my MVC controllers will have to pass raw numerical information between my business entities and my (presumably static) statistics classes. This is quite a neat separation but potentially means a lot of business logic still remaining in the presentation layer.
Create a Statistics project; however, create a tight coupling between the classes in this project and my business entities. For example, instead of passing a Reading object's values into a method, I will pass the entire object (or define them as extension methods). This will shift business logic out of my MVC app but the tight coupling seems a bit messy.
Keep all of my business logic inside my service layer. Define strongly-typed subclasses of EntityService, so my services contain both entity-specific business methods and data storage methods, while keeping the entity classes themselves as pure data containers. Create a separate Statistics project for any generic statistical processing and call its methods via my derived service classes. My service classes effectively merge business functions with the storage functionality provided created by IRepository<T>.
I am erring toward the third option but does anyone have any thoughts? Alternative suggestions?
Thanks in advance!
Preliminary observation:
I like the way in which you described your project, I just didn't get why your Data Access Layer (DAL) is called NHibernate Layer: it is odd with all the rest in which you didn't use technology name to describe a logical layer (correctly). So I suggest you to rename it DAL, and use it to abstract your app from NHibernate.
My opinions about your questions:
Absolutely no. It is good to apply Dependency Injection to All Layers. A couple or reasons for which it is good:
1.1 Testing: you can mock DAL interfaces and do unit test Service Layer w/o DAL using another DI config file. In the same way you can mock Service for Web Controllers layer and so on.
1.2 Different DAL implementations: suppose you need different DAL implementation (NOSQL, SQL or LINQ instead of NHibernate, etc..) technologies for different deployment of you project or to scale in the future. You can do that easily maintaining different DI config files.
You can have the same layer deployed in different projects. In the same way you can have a project containing different layers. I think their relation is orthogonal: project is describing a physical (development time and run time) implementation. Layers are logical. So initially I would keep it simple with the third option.
I just don't understand why you saying the following regarding this option:
Create a separate Statistics project for any generic statistical
processing and call its methods via my derived service classes. My
service classes effectively merge business functions with the storage
functionality provided created by IRepository.
I see Statistics as one or more services so you can implement it as namespace with classes inside your Service Layer. And, as any other service, you can inject DAL Repository classes. And, as any other Service/DAL, the Model classes can be shared between different Services and DAL classes.
StatsService.AverageReadingFor(Person p, DateTime start, DateTime end) sounds good.
There are several implementation options:
Using underlying repository features (for example: SQL avg function)
Using Observer Pattern which is implementable also using Dependency Injection
Using Aspect Oriented Programming. See that Spring.Net chapter as an example.
If you have more than one Service Layer instance (more than one server) than 2 and 3 must be adapted for out of process communication using a messaging system.
Just an update - Regarding my second question, I have decided to define an IStatsService<T> which expects an IEntityService<T> to be passed into its constructor. I'll use this for generic statistical processing of business entities and create further interfaces that implement IStatsService<T> where I need more type-specific information.
Hopefully this will help someone who has been scratching their head about a similar problem!

Regarding DDD Structure and Layering.

Folks,
Apologies if this has been covered in another thread, but I have searched ddd and mvc articles and have not found a straightforward answer.
I am hoping to apply a DDD approach to the architecture of my MVC projects. Please correct me where I am wrong.
All MVC controller actions that involve hitting the domain model will initially hit
and application service layer.
The application service layer here acts as a facade between presentation and the domain.
Any requests from the application service later that clearly involve discrete domain aggregates will perform fetch or modify operations on aggregate roots using repositories. Each aggregate root will have its own repository.
so the application service layer must be injected with any/all repositories required by the domain.
Where an operation may involve multiple aggregates or requires logic that does not fit neatly into one aggregate, the application service will call a domain service to carry out operations across aggregates.
This does not seem right to me.
My confusion is that from a DDD perspective Im not sure whether for example aggregate roots should perform their own persistance i.e. the aggregate gets injected with a repository and then persists/fetches itself or whether as above the application service layer uses repositories to act on or fetch aggregates?
Also if the application service layer is injected with all repositories, does the domain service that the application service layer calls also need repositories injected?
Im keeping CQRS out of this at this point. I want to get the layering and the relationship between services and aggregates sorted out first.
Thanks for any advice.
All MVC controller actions that involve hitting the domain model will
initially hit and application service layer. The application service layer here acts as a facade between presentation and the domain.
There's debate over that but I would consider carefully whether that additional layer is needed or not. It adds a lot of boilerplate code and degrades maintainability - as someone pointed out recently, when you separate things that change for the same reasons (ie your service methods and the corresponding domain methods), you have to make changes in many different places in the system.
On the other hand, you could need that service layer to map your domain objects to DTOs but there again, it could be done directly in the Controller and nothing forces you to use DTOs in the presentation layer.
My confusion is that from a DDD perspective Im not sure whether for
example aggregate roots should perform their own persistance i.e. the
aggregate gets injected with a repository and then persists/fetches
itself or whether as above the application service layer uses
repositories to act on or fetch aggregates?
It's usually considered bad practice to have aggregate roots manage their own persistence because it breaks persistence ignorance and violates the Single Responsibility Principle. If you do that, your aggregate root class now has 2 reasons to change, 2 reasons to break the code, it is less maintainable, etc.
You should instead delegate the responsibility of saving the aggregate root in its repository to an object that will be aware of the application execution context (for instance, a Controller or an object in the Application layer).
Also if the application service layer is injected with all
repositories, does the domain service that the application service
layer calls also need repositories injected?
Yes, I think it pretty much makes sense especially if the domain service heavily relies on the repository.

Where should "#Transactional" be placed Service Layer or DAO

Firstly it is possible that I am asking something that has been asked and answered before but I could not get a search result back. We define transactional annotations on service layer typical spring hibernate crud is usually
Controller->Manager->Dao->Orm .
I now have a situation where I need to choose between the domain model based on client site.
Say client A is using my domain model all is good but then an other client site would give me a web service and not be using our domain model.
Which layer should I be replacing . I believe it has to be DAO which will be getting me data from web service and sending it back.i.e two separately written DAO layers and plugged in based on scenario.
I have now realized that we have been doing tight coupling (if there is such a thing or say not having loose coupling) when we put #Transactional in Service layer. So many brains can not be wrong or are they (I doubt it).
So question is "Where should "#Transactional" be placed Service Layer or DAO ?" and is it service layer downwards I should be replacing.
Eleven years on and still relevant . If I look back at the project somethings were obviously wrong with my understanding of Domain model back then . I was regarding ORM layer as domain model and we wanted to work with ORM and detached entities and no have any data mapping and not have any DTOs. That was the trend those days. These days Domain Model is not the ORM and having a proper Domain model and using ORM or Webservices are datasources take care of this issue. Like many pointed out yes Service is the right place for it and have proper domain model and not regard JPA (ORM) as domain model.
Ideally, Service layer (Manager) represents your business logic and hence it should be annotated with #Transactional.
Service layer may call different DAOs to perform DB operations. Lets assume a situation where you have 3 DAO operations in a service method. If your 1st DAO operation failed, other two may be still passed and you will end up with an inconsistent DB state. Annotating Service layer can save you from such situations.
You are going to want your services to be transactional. If your DAOs are transactional, and you call different DAOs in each service, then you would have multiple transactions, which is not what you want. Make the service calls transactional, and all DAO calls inside those methods will participate in the transactions for the method.
i will suggest to put #Transactional in Service layer methods since we can have multiple DAO implementations. by using this we can made our services will be transactional. refer
best practice is to use A generic BasicService to offer common services.
The Service is the best place for putting #Transactional, service layer should hold the detail-level use case behavior for a user interaction that would logically go in a transaction. in this way we can have maintain separation between web application code and business logic.
There are a lot of CRUD applications that don't have any significant business logic, for them having a service layer that just passes stuff through between the controllers and data access objects is not useful. In these cases we can put transaction annotation on Dao.
So in practice you can put them in either place, it's up to you.
By having multiple calls in your service you need #Transactional in service. different calls to service will execute in different transactions if you put #Transactional in service.
It's of a personal choice based on application types, if application is layerd across many modules and majority of operations are #CRUD based ,then having #transactional annotation at service level makes more sence.. engine type application like schedulers , job servers,#etl report apps, where sessions and user concept does not exists, then propagational transaction at context level is most suitable... we should not end up creating clusterd transactions by putting #transactional every where ending up transactional anti patters...anyways for pragmatic transaction control JTA2 is most suitable answer...again it depends on weather you can use it in a given situations...
You should use #Transactional at service layer, if you want to change the domain model for client B where you have to provide the same data in a different model,you can change the domain model without impacting the DAO layer by providing a different service or by creating a interface and implementing the interface in different model and with the same service populate the model based on the client.This decision is based on the business requirement and the scope of the project.
i have heard in a programming class,that dao layer is responsible for interacting with database, and service is a set of operations might be with dao and therefore database or not and that set of operation is in one transaction, mean is better service be transactional.

Inversion of Control, Spring Framework - system of global instances

Is inversion of control essentially just retrieving a set of already instantiated objects? In theory. I guess more granular details as implemented by IoC frameworks like Spring have a lot more functionality, but in theory it seems like IoC containers operate like a collection of instantiated beans (in the Java world) and then you get access to those beans. Almost like you would with a collection Singleton objects?
It's partly getting hold of singletons in practice, yes. Some beans will be instantiated multiple times, whenever they're needed (depending on the configuration), but often you can make do with single instances - particularly if they're stateless once configured. I like the idea of data flowing "through" an application's plumbing after it's been properly hooked up.
The benefit is that the "singletoneity" is only present in the configuration, not in the code, which makes the system more testable and flexible. The difference in terms of how you view (and expose) the dependencies with your app is huge.
Although the answer has already been accepted, I will elaborate a little more:
Initially spring was mostly about singleton management. with the introduction of custom scopes came the web specific scopes and the ability to create your own custom scopes. Leaning on AOP features this also allows you to "stay singleton" for as long as possible, because it uses a technique known as scope proxying. This can let you introduce a scoped object right in the middle of a chain of singletons - a feature you'd often be using threadlocals for.
So I'd say it's about tight control of instance creation, to make sure everything is done only the required number of times, and preferably only the construction that is necessary is done for each request. Singleton management was the old days.

What are the advantages and disadvantages of the Session Façade Core J2EE Pattern?

What are the advantages and disadvantages of the Session Façade Core J2EE Pattern?
What are the assumptions behind it?
Are these assumptions valid in a particular environment?
Session Facade is a fantastic pattern - it is really a specific version of the Business Facade pattern. The idea is to tie up business functionality into discrete bundles - such as TransferMoney(), Withdraw(), Deposit()... So that your UI code is accessing things in terms of business operations instead of low level data access or other details that it shouldn't have to be concerned with.
Specifically with the Session Facade - you use a Session EJB to act as the business facade - which is nice cause then you can take advantage of all the J2EE services (authentication/authorization, transactions, etc)...
Hope that helps...
The main advantage of the Session Facade pattern is that you can divide up a J2EE application into logical groups by business functionality. A Session Facade will be called by a POJO from the UI (i.e. a Business Delegate), and have references to appropriate Data Access Objects. E.g. a PersonSessionFacade would be called by the PersonBusinessDelegate and then it could call the PersonDAO. The methods on the PersonSessionFacade will, at the very least, follow the CRUD pattern (Create, Retrieve, Update and Delete).
Typically, most Session Facades are implemented as stateless session EJBs. Or if you're in Spring land using AOP for transactions, you can create a service POJO that which can be all the join points for your transaction manager.
Another advantage of the SessionFacade pattern is that any J2EE developer with a modicum of experience will immediately understand you.
Disadvantages of the SessionFacade pattern: it assumes a specific enterprise architecture that is constrained by the limits of the J2EE 1.4 specification (see Rod Johnson's books for these criticisms). The most damaging disadvantage is that it is more complicated than necessary. In most enterprise web applications, you'll need a servlet container, and most of the stress in a web application will be at the tier that handles HttpRequests or database access. Consequently, it doesn't seem worthwhile to deploy the servlet container in a separate process space from the EJB container. I.e. remote calls to EJBs create more pain than gain.
Rod Johnson claims that the main reason you'd want to use a Session Facade is if you're doing container managed transactions - which aren't necessary with more modern frameworks (like Spring.)
He says that if you have business logic - put it in the POJO. (Which I agree with - I think its a more object-oriented approach - rather than implementing a session EJB.)
http://forum.springframework.org/showthread.php?t=18155
Happy to hear contrasting arguments.
It seems that whenever you talk about anything J2EE related - there are always a whole bunch of assumptions behind the scenes - which people assume one way or the other - which then leads to confusion. (I probably could have made the question clearer too.)
Assuming (a) we want to use container managed transactions in a strict sense through the EJB specification then
Session facades are a good idea - because they abstract away the low-level database transactions to be able to provide higher level application transaction management.
Assuming (b) that you mean the general architectural concept of the session façade - then
Decoupling services and consumers and providing a friendly interface over the top of this is a good idea. Computer science has solved lots of problems by 'adding an additional layer of indirection'.
Rod Johnson writes "SLSBs with remote interfaces provide a very good solution for distributed applications built over RMI. However, this is a minority requirement. Experience has shown that we don't want to use distributed architecture unless forced to by requirements. We can still service remote clients if necessary by implementing a remoting façade on top of a good co-located object model." (Johnson, R "J2EE Development without EJB" p119.)
Assuming (c) that you consider the EJB specification (and in particular the session façade component) to be a blight on the landscape of good design then:
Rod Johnson writes
"In general, there are not many reasons you would use a local SLSB at all in a Spring application, as Spring provides more capable declarative transaction management than EJB, and CMT is normally the main motivation for using local SLSBs. So you might not need th EJB layer at all. " http://forum.springframework.org/showthread.php?t=18155
In an environment where performance and scalability of the web server are the primary concerns - and cost is an issue - then the session facade architecture looks less attractive - it can be simpler to talk directly to the datbase (although this is more about tiering.)

Resources