EntityBean, SessionBean, databean and accessbean - java

I have been trying to learn about the Java beans in WebSphere Commerce but I got really confused. Please help me out. I need to know:
What is the difference between EntityBean, SessionBean,
DataBean and AccessBean and how do they compare?
Though I found the difference between Session and Entity, and between Access and Data, I fail to understand how they are all related to each other.
All the help would highly be appreciated.

The entity bean represents a java bean which is coded by EJB specification and this java class is used to identify a record in a table.
Session bean is also a java bean following the EJB specification ; but this bean can be considered equivalent to a java class which has business logic with or without interacting with entity bean(i.e DB Data). Therefore a Session bean e.g ProcessRegistrationBean will act on a entity bean e.g PersonBean.
Now, for the second part of the question on what is access and databean : these two beans are extensions of Entity beans provided by Websphere application providing convenient access to the entity beans hiding the complexity of JNDI lookup and home/remote interface methods of EJB spec.
This means that if you want to get a user's info, you can easily do so as just creating the UserAccessBean(which is generated from entity bean for user) via it's no arg constructor and then initialize by setting the user id. AccessBean behind the scenes uses home interface to access remote interface and all those EJB stuff happens without you need to know them explicitly - therefore making it easier for the developer.
Databean are extensions of its corresponding access beans i.e UserDataBean extends UserAcessBean.
The suggested use of AccesBean is in the java layer e.g SessionBean (this also means you don't have to deal with entity bean directly ) and DataBean in the JSP layer. This is how all these are related

In Java nearly any class is called a bean. So don't confuse with that.
The different bean-terms you show are concepts of the function a class has in your application.
Usually the entity bean represents some entity of your domain. A user, a book, a car or what ever. Usually having some properties (firstname, lastname etc). An abstracted (or conceptual) object of your domain.
Unfortunately in EJB entity bean is meant as a bussiness controller for a domain object handling all complex actions that a domain object can be involved into (like create new book with dependencies, sell book, order book and whatever your domain allows to do with a book). All of your use-cases.
The domain object itself (a book) with its properties (title, ISBN number, price, amount of pages) is represented by a data bean, which usually maps to some database tables and rows.
The session bean usually is some kind of a container for information bound to the session of a user (and thus has some lifecycle, as the users session will expire). This could be information, if the user is authenticated or which data the user is currently editing. Therefor the session bean should have a pointer to a entity bean representing the users core data.
The access beans seem to be some clones on the "Data Access Object / DAO" pattern. This are application wide classes that allow you to access entities by providing methods like "getUserByUsername" or find methods for different searches and encapsulate accessing databases and other storages.

Related

How to design and validate access to a sub-resource in a jax-rs REST API avoiding code duplication?

Specifications
I'm currently developing a JavaEE app using JAX-RS and in the process of exposing various resources I'm faced with the following design dilemma that I haven't found a proper answer to.
Two entities, Customer and Address, are interconnected with the One-To-One, Total
Participation relationship, meaning one Address per Customer. Deriving from these I created a resource CustomerResource that exposes various endpoints relating to the Customer entity that lead to basic CRUD operations. Some of these endpoints are:
POST (/customers/create)
GET (/customers/get)
GET (/customers/get/{id})
PUT (/customers/update/{id})
DELETE (/customers/delete/{id}
The problem arises when I create the second resource AddressResource which will handle endpoints relating to operations for the Address entity. This entity cannot exist without a Customer and as such I came to the decision to convey that using nested URI scheme, as opposed to using QueryParams. Now, as you can imagine, some of the endpoints that the AddressResource exposes are:
POST (/customers/{id}/address/create)
GET (/customers/{id}/address/get)
PUT (/customers/{id}/address/update)
DELETE (/customers/{id}/address/delete)
I'm faced with validating IF the Customer ID exists and then continuing on to the actual operation that the endpoint entails. Looking the app design from a top down viewpoint, right after the Resource classes come the Service classes. For each Resource class there is a Service class which carry out any necessary business logic and call for the DAO classes to reflect all the necessary changes to the physical DB and the persistence context. So, any validation happens on the Service layer. The thing is that the AddressService class will have to make a call to check if the Customer exists using the CustomerDao class, which queries the database for the given customerId and returns its findings. If the customer exists then the AddressDao gets called to perform the corresponding query on the DB relating to the Address entities.
So, in a sense, I want to avoid the coupling of the Service classes passing calls to multiple Dao classes, as well as, avoid any duplicate code that validation for multiple resources might lead to.
This is due to the fact that I want to introduce a new One-To-Many resource that also requires validation on the customerId level and this would entail its Service class also calling the CustomerDao. I'm aware of the N+1 query problem and I'm keeping the nested resource depth at a maximum of 2. The validation would have to be performed regardless of the URI design as it derives from the Total Participation rule.
Sry for the long and maybe oversimplified explanation of the problem and thank you all in advance!
First, "One-To-One, Total Participation relationship, meaning one Address per Customer" also means "just one Customer at one Address". In this case you don't need separate Entity for Address, it might be the part of Customer.
So, let me suppose, you meant One-To-Many relation: "many Customers at one Address". Didn't you? In this case you can create Addresses as a dictionary with separate resource then bind that to some Customers with web-method of Customer resource.
Finally, to avoid code duplication you can encapsulate business logic within appropriate facades then inject those anywhere you need like:
#Inject
CustomerFacade customerFacade;
...
customerFacade.bindAddress(customerId, addressId);

Should I create many singletons or singleton context with references to my state and objects?

I am using Guice in a project. Since it is the first time, I am wondering about how to keep and pass around state, i.e. objects that contain some user input or long lived objects that are needed elsewhere (not where they were injected the first time).
For instance, my application has a Server which the user can start and stop. Furthermore, the user can enter some data which leads to state that needs to be preserved in memory.
At the moment I see two possibilities:
have a Context class with scope #Singleton and some references to other classes that keep my state and offer me certain functionality.
The Context class would give me access to the Server instance, to user data, other services etc.
The instances of the Context may be injected by Guice.
Thus, if I want to stop my server, I would require the Context as a dependency (and not the server).
This goes a bit against the recommendation on the Guice website (inject direct dependencies instead of accessing the "real" dependency with chained getters).
annotate all classes with #Singleton that should exist only once and are injected in several other classes. As a consequence, I would have only a singleton server, somewhere a class with the user data, etc.
The singleton pattern (GoF) is said to be bad design. Thus, I am wondering whether I should minimize the use of #Singleton or whether this is a different story using Guice respectively dependency injection in general.
Are there any other possibilities or a better approach?
I think most of your questions is related to Dependency Injection Paradigm. first of all Using DI doesn't mean every managed bean should be Singleton. The managed beans have their own life cycle. they can be instantiated on every access / request / session or being singleton.
The other thing you should be care about is with DI we usually wire-up our main application design. you should think of your domain objects and their relations instead of DI(Guice/Spring).
for instance in your case if you need a Service Object in a bean so you have the relationship between these two classes and no need to to have a relation to Context!
if data inserted by different users are visible to all users so make the service singleton in your application. if the states of Server bean for each user are different so make the scope of bean Session to allow every user have his own Server bean.

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.

EJB: seems I don't understand the crucial point

I'm new in EJB & persistence at all, so excuse me please if I'll ask a stupid question.
I read a book about EJB and JPA, and faces phrase that I don't understand at all:
Intended to fully insulate developers from dealing directly with
persistence, it (EJB) introduced an interface-based approach, where
the concrete bean class was never directly used by client code.
Instead, a specialized bean compiler generated an implementation of
the bean interface to facilitate such things as persistence, security,
and transaction management, delegating the business logic to the
entity bean implementation.
and
The notion of container-managed entity beans was introduced, where
bean classes became abstract and the server was responsible for
generating a subclass to manage the persistent data.
What does it mean:
Specialized bean compiler generated an implementation of the bean interface
server was responsible for generating a subclass to manage the persistent data
Actually I can't grasp what mean generate implementation/subclass, does it mean in runtime?
Thank you in advance.
EDITED:
Finally, entity beans were modeled as remote objects that used RMI and
CORBA, introducing network overhead and restrictions that should never
have been added to a persistent object to begin with.
Does it also sink into nothingness?
1) Interfaces: To define a bean, you had to declare a Local interface and a Remote interface (if you were writting bean MyEJB, they had to be MyEJBLocal and MyEJBRemote; MyEJB would implement both). With that, the compiler generated some derived class implementing the methods, such methods would just connect to the EJB server to retrieve a bean and execute its methods.
I am not so sure about 2, since we had so many performance issues that we ended implementing JDBC logic in the Session beans (I know, I know)...
Specialized Bean: Since Java EE 5, EJB turn into annotation #EJB. All annotaion works like interface. This simple annotaion provide security, and transaction management, delegating the business logic at compile time.
JPA: No more entity bean remain since Java EE 5. Now if you put #Entity to on pojo than server will generate container-managed entity beans and communicate with database through persistance context.

.java terms and random words clarification

Im really new to java, jsf, jsp, and I need to learn how it works quickly. So the website Im using to practise has some terms etc that I dont know what they mean and Im hoping somebody can explain what they mean and how/what they are used for:)
Requestscoped
Applicationscoped
Sessionscoped
EntityManager
and could someone walk me through what these lines do?
#RequestScoped
public class Dao {
#DataRepository
#Inject
private EntityManager entityManager;
First of all, in Java (5 and higher), "things" starting with a # (e.g. #Deprecated) are called annotations.
Annotations provide data about a
program that is not part of the
program itself. They have no direct
effect on the operation of the code
they annotate.
Your JavaBeans needs to be configured to a scope if you want to use it in JSF (Definitions can be found here).
#RequestScoped: Objects with this scope are visible from the start of the request until the end
of the request. Request scope starts at the beginning of a request and ends when the
response has been sent to the client. If the request is forwarded, the objects are visible
in the forwarded page, because that page is still part of the same request/response
cycle. Objects with request scope can use other objects with none, request, session,
or application scope. If you have to think it in terms of servlet, the managed bean is stored in the HttpServletRequest until the end of the request (when the response is sent to the client). After that, the bean no longer exists in the request.
#SessionScoped: An object with session scope is visible for any request/response cycle that
belongs to a session. Objects with this scope have their state persisted between
requests and last until the object or the session is invalidated. Objects with session
scope can use other objects with none, session, or application scope. Basically, these objects are stored in a HttpSession (refer to Servlets again). Each session has a session ID (known as JSESSIONID) that the bean is associated with.
ApplicationScoped: An object with application scope is visible in all request/response cycles
for all clients using the application, for as long as the application is active. In terms of Servlet, this could be, managed bean stored in a ServletConfig.
#NoneScoped: Objects with this scope are not visible in any JSF page. When used in the configuration file, they indicate managed beans that are used by other managed beans in the application. Objects with none scope can use other objects with none scope.
For EntityManager, this is associated with persistence context. It is used to create and remove persistent entity instances, to find entities by their primary key identity, and to query over all entities. For more, refer to the JPA (Java Persistence API) Specification, or Hibernate.
#Inject, means that the instance is injectable. They follow the infamous crase word of Depency Injection or Inversion of Control (IOC). What this basically mean, is that when the resource (in your case EntityManager entityManager is needed, the JEE container instantiates the resource for you (without you needed to instantiate it directly through e.g. a constructor, etc.).
I have no clue what #DataRepository means. Never seen it before.
I hope this helps you.
These terms are usually associated with a dependency injection framework like guice and not with java in particular.
http://code.google.com/p/google-guice/wiki/Scopes describes the various scopes that are built into guice.
By default, Guice returns a new instance each time it supplies a value. This behaviour is configurable via scopes. Scopes allow you to reuse instances: for the lifetime of an application (#Singleton), a session (#SessionScoped), or a request (#RequestScoped). Guice includes a servlet extension that defines scopes for web apps. Custom scopes can be written for other types of applications.

Categories