Differences between Container Managed and Application Managed EntityManager - jpa-2.0

I have a problem to understand the differences between container-managed and application-managed entity manager?
I would be very grateful if you can give me an example that illustrates the differences.

For a container-managed entity manager, the container manages the life-cycle of this entity manager. For an application-managed one, the application (meaning you, the programmer) manages this.
A simple but very visible difference is that you must call close() on an application-managed entity factory. When you use a container-managed one, the container does this for you.
The persistence context of an application-managed entity manager is also not transaction scoped. It starts when the entity manager is created and ends when it is closed. This makes it somewhat like the extended persistence context, with the difference that you can use this type of entity manager everywhere, not just in stateful beans.
Finally, application-managed entity managers are the only ones that can be officially configured to use resource-local transactions, which are independent of any (JTA) transaction the container might have running.
Note that in Java SE you only have application-managed entity managers. So, when you just add Hibernate to Tomcat (a popular combination), you're essentially working with application-managed entity managers all the time.

If you have multiple java EE application connecting same database and using JPA entity manager cache. you may face this issue:
Database changes made in one application may not reflected in other applications immediately
Use application managed entity manager instead of container managed entity manager is the perfect solution to resolve this issue.
You may refer to my blog Java EE Example - How to use application managed entitymanager

Related

Drupal 8: What are services?

Are services simply a way to share an instance of a class?
I have looked at the following documentation:
https://www.drupal.org/node/2133171
https://ffwagency.com/digital-strategies-blog/drupal-8-services-dependency-injection-and-decoupling-your-code
I will give you a quick introduction & concept but with the links you have you should be able to fully understand the potential.
Concept
The concept of services is to decouple reusable functionality and makes these services pluggable and replaceable by registering them with a service container.
Your application is full of useful objects: a "Mailer" object might help you send emails while another object might help you save things to the database. Almost everything that your app "does" is actually done by one of these objects.
These useful objects are called services and each service lives inside a very special object called the service container.
$entityManager = $container->get('entity_type.manager');
The container allows you to centralize the way objects are constructed. It makes your life easier, promotes a strong architecture and is super fast!
The Symfony 2 documentation has a great introduction to services.
Usage
You can also organize your own code into services. For example, suppose you need to show your users a random, happy message. If you put this code in a controller or a block, it can't be re-used. Instead, you can create you own service.
You can find all the service that Drupal 8 expose on this documentation page: https://api.drupal.org/api/drupal/services.
With all the links below & the introduction upper, you have everything to well understand & start using services:
Services and dependency injection in Drupal 8
Drupal 8 Services, Dependency Injection, and Decoupling Your Code
Structure of a service file
Collection of documentation about Servie in Drupal 8
I wish you all the best using Drupal 8 !

How can a web service talk to the server without accessing the server database?

I need to design a webservice for a data collection service - and the requirement is that the webservice should not access the database directly.
The web service will talk to the data collection service which in turn will access the database. So is HTTP the only option for web services to talk to the data collection service? But the data collection service is yet to be developed - is there a design that should be followed for the web service to be able to talk to this service? I want to make sure that the data collection service is implemented properly so that I can do my part of the web services without too many hassles.
Think of the "web service" as any application in this case. The code which accesses the "data collection service" should work in any application, after all.
The "data collection service" is an external dependency to the application. As such, it should be abstracted behind a service facade. An interface, for example. (I'm going to use C# in my example, since I'm most familiar with that.) Something like this:
public interface IDataCollectionService
{
void CollectData(SomeDataDTO data);
}
At this point, all code which uses the data collection service should use this interface type. Until the data collection service is developed, you can use a mock data collection service. Any in-memory implementation with just enough functionality to keep you going would work. For example:
public class MockDataCollectionService : IDataCollectionService
{
public void CollectData(SomeDataDTO data)
{
// do nothing
}
}
This implementation would have no side-effects, throw no errors, and just assume that everything in the external dependency worked as expected. You can edit/expand this mock to result in error conditions, etc.
(Note that I'm kind of using the word "mock" is a more generic way than purely unit testing terms. This happens a lot in the industry, actually. For your unit tests themselves, you could use any mocking library to create an actual unit test mock by using the above interface.)
This is all just an example, and how you structure it is entirely up to you. The point is that, as an external dependency, all interactions with the data collection service are behind a facade. Then, when that service is developed, it won't really matter what protocols and standards it uses. When you create a new DataCollectionService class which implements the interface, all of the code for using those protocols and standards would be encapsulated within that class. The rest of the project won't know or care the difference.
Then, when that implementation is ready, you can just swap it out with the "mock" implementation and test the system without having changed any other code in your application. If, at a later time, it's decided that the protocols need to change again, the only thing you'd need to change (or create a new one of) is that one class which implements the interface.
Indeed, if you ever are granted permission to access the database, all that would need to change is to again build a new implementation of that interface. Essentially, whether you can or can not access the database is just as immaterial as what protocols are being used. The architecture of the software abstracts it, so that the architecture of the infrastructure has as little impact as possible.
You can create a mock object that mimics the data collection service, until the actual service is completed. The mock object can double as a testing tool while you create your unit tests.

Domain object construction responsibility: Should I use domain objects in service layer interface?

When designing a service layer, should I use my domain objects in the interface contract? For example:
public void registerUser(String username, String realName)
VS
public void registerUser(User user)
Should the domain objects be constructed in the client code or behind the service facade?
I'm using EJB and my clients would be a locally deployed web application, RMI client and maybe a web service client.
Technically, there's no problem in using one or another: Web Service through XSD is capable of supporting primitive types like Strings and complex objects like your User class.
Now, what if your User class has 20 attributes and you only need username and realName to register a user? In that special case it would be better to use your first approach because less bandwidth is needed are your not forcing your client that construction of a big XML document that's not needed.
Other scenario is that your User class produce a complex and highly-nested XML document according to JAXB rules. That can produce complex messages for your client and also complex client-implementations. If that's the case, you could use a simpler version of your Domain Class -maybe with one or two nesting levels- as a DTO to simplify message interchange.
In my opinion, Service layer in general shouldn't use domain objects. Domain is something that handles business logic, rules and workflow, while service provides an interface to it.
The simplest principle when designing service layer is "service method realized a single use case". (Use case is a scenario with both inputs and outputs defined pretty well).
In your sample - registerUser(String username, String realName) - looks completely fine. Service would instantiate all required domain objects and initiate business operation - in the same time, service clients are unaware of business logic internals (for example, there could be some specific in User object construction, etc.)
Passing Domain objects as part of the Service layer is a way much simpler and more object oriented.
Working with the user input values and constructing relevant Domain objects - is the responsibility of the Controller layer
Moreover Service layer describes the API to be used by end Clients. If the Service layer starts exposing API with generic types (like String, Maps etc) then trouble starts.
Instead of DTOs which is an anti-pattern Domain objects are better equipped to be passed from Controller layer to Service Layer.
There seems to be no harm in passing the User object through-out all your services. According to DDD (Domain Driven Design http://en.wikipedia.org/wiki/Domain-driven_design ) this is a very good practice and all your domain object should available across all the layers in your project. In the long run it will make you code more object oriented which is usually seen lacking in a typical Java EE project (aka anemic domain model) but the only additional recommendation is you try to keep business logic within the User class and not in your service.
In my opinion, it is not suitable to expose domain object from facade layer. Clients that are using the service should not be depended to domain objects. It is better to designing a data contract and expose them from facade layer. They will be used just for transferring data, and that is DTOs.
Consider that domain objects are not just DTOs and they can provide some functionless.
Also a service in facade layer expose a usage of system and it may includes the collaboration of some parts of multiple domain objects and sometimes there may be not a suitable mapping between the requirements of the method in facade layer and available domain objects.
Also DTOs and their structure may require some considerations for network performance reasons. And these considerations usually are not meaningful in designing domain objects.
Should the domain objects be constructed in the client code or behind
the service facade?
Domain objects should be created on service side. Client merely passes all parameters required to create an object.
A general algorithm of object construction is:
Get parameters
Validate parameters
Pass valid parameters into object constructor to get a valid object
Register a valid constructed object in repository for persistence (if necessary)
If an object is created on client side and passed to service, then several problems rise:
The object from client side may be in the incorrect state (client data can not be trusted)
Object state has to be validated
Validation of an existing object means possible duplication of validation logic, possible loss of encapsulation when private field values are validated or sometimes single responsibility principle violation
Sometimes service has to reconstruct the object using passed object property values as parameters

Stateful Webservice vs. (Stateful Bean + Stateless WS)

I have a system module in my design which must maintain its state. On the other hand I need to provide a public access to it through a web-service.
What is better to do in such a situation. Create a stateful bean which can be controlled by a stateless web-service or create a statefull web-service.
It's better to maintain core functionality(state) within your module & let others access it, but can't alter it. Also in case of changes, it will be limited to your module only, others will remain unaffected.
Performance wise also, I think it will be better to use statefull beans as web-services are called remotely & may loose the state in case of network failure etc.
They are mainly developed to interact with homogeneous/heterogenous applications and to decouple the functionality, mainly to consume/expose a service which further processes the business logic.
Also, if you are adding new external modules in future, they don't have to reimplement the functionality for maintaining state & can just reuse it.

Weblogic WebService with EJB

I am going to develop a webservice which will expose two operations. These operation will query/update data from database.
Please suggest do i use EJB for database operation and what advantage i will get?
or
in my webservice i use JPA directly like following, and create my entities and persist them
#PersistenceUnit private EntityManagerFactory emf;
#Resource
private UserTransaction utx;
Please answer with advantages/disadvantages.
Regards,
imran
Both approaches are valid and supported by Java EE, so this is only a design recommendation based on my experience:
Do never directly expose EJB operations as Web Services, it only increases runtime complexity. If you publish an EJB as a Web Service the container must still wrap it by using an internal Web Services servlet which (implicitly) tightly couples your WAR containing the internal Web Service mapping to your ejb-jar (depends on app server product). Furthermore, it's hard to debug in day-to-day operations.
My recommendation using only standard Java EE features without any additional libraries:
POJO defines the Web Service interface, aka its operations (#WebService annotation). It delegates to a functional implementation. Let's call this POJO WS-POJO.
Two options to implement the functionality:
WS-POJO calls stateless Session Beans which provide the required functionality. Pro: All EJB features available (dependency injection, declarative transaction mgmt, etc.). Con: "Heavyweight"
WS-POJO calls custom POJOs following e.g. the Command Pattern. Pro: "Lightweight". Con: Dependency injection not possible; Entity Manager etc. to be passed.
Today, I'd go with option #1... my 2 cent