About Enterprise Java Session Beans - java

Being completely new to Enterprise Java development and after reading the following tutorial.I managed to develop my first session bean. After reading a little about session beans I do have some questions about it (session bean) and I hope the experts out here could help me out.
Normally in a servlet scenario without using EJB we would do something like the following to accomplish a certain task
StudentList stud = businesslayer.businessMethod_GetStudentsFromDb();
Now the businesslayer would call the service layer which would get the details from the DB and return it.
Now my questions are as follows:
1-If I were to implement this mechanism using say a stateless EJB will I have to copy the domain package which contains the domain object StudentList to the "-ejb" folder of my enterprise project (I am using netbeans).Similarly will I have to copy other Business methods from the source folder of my "-war" folder to the ejb folder just so that the stateless bean in the "-ejb" folder can use those methods. Cant classes inside the "-ejb" folder use classes insider the source folder of the "-war" folder.
2-This is the question so far i could not understand. What advantage would i get if i used EJBs instead of my current mechanism ?

1
If you're building a single application, there's nothing you need to copy. If you want to have a very strict separation between business code and web/view code you can create an ear, with an ejb module and a web module. All classes in the web module can access all classes in ejb module, but the reverse is not true. This effectively imposes a layering in your application.
But you don't have to go for this separation. You can also just put your EJB beans in a single war together with your Servlets and what have you. There's no restriction on where you put your beans. It can be in a separate package, or in the same package as your Servlets.
You might wanna look at this example I made: http://arjan-tijms.omnifaces.org/2011/08/minimal-3-tier-java-ee-app-without-any.html. There, BusinessBean is an EJB that resides in the same (default) package as the JSF backing bean in a single war.
In the single war setup, everything can access everything. Do note that even in this situation you probably would like to keep your business code "clean" and keep things like HttpRequest and such out of it.
2
EJB beans, especially EJB light, provide exactly those things that most every web application needs: transactions, pooling, thread-safeness, security and injection. You'll get the most out of EJB beans when combined with JPA. The advantage is that your code will be much less verbose and at the same time shielded from race conditions and inconsistencies that you'll run into when using plain JDBC.
E.g.
#Stateless
public class CustomerService {
#PersistenceContext
private EntityManager entityManager;
public void addCustomer(Customer customer) {
entityManager.persist(customer);
}
}
Without EJB you'll need a bunch of try/finally blocks which open and close the connection, start and commit the transaction etc. And without JPA you'll have a large block of tedious code that inserts individual fields of the Customer entity shown in the example into a prepared statement.
If you (later) have services that call one or more other services and either everything needs to be saved to the DB or nothing (as opposed to something undefined in between), then this is quite a challenge to accomplish in plain JDBC. You'll have to pass open connections around and need special variants of each service method that opens/closes connections and starts/commits transactions in addition to methods that can be used in an intermediate phase. Before long, this will become highly complex and a big ball of mud.
With EJB, every method in an EJB bean that you call from within an other EJB bean automatically joins the ongoing transaction or starts its own if no transaction is in progress. This alone massively simplifies many common business tasks carried out by typical web applications.
Don't let anyone tell you that only "enterprise applications" need transactions, and web applications don't need this. This is simply not true. A transaction is a very basic thing when doing DB operations, at the same level of basic requirements as primary keys or foreign keys are. When performing business logic for say an order (in a webshop), you definitely don't want your inventory being decremented, but no actual order being send, or an order being send but no money subtracted from your customer's account, etc etc. The simplest of business logic often involves writing to at least two tables, and every time that happens you'd better be using transactions.
Do make sure you're using EJB 3 though. Stay far away from everything that has to do with EJB 2. Don't even touch things like home interfaces or Entity Beans, which have been deprecated for some 6 years now. (don't confuse EJB Entity Beans with JPA Entities though, despite the unfortunate name similarity these are completely different. JPA Entities are very sane and useful)

Related

Manage multiple models in multiple controllers to keep track on them

I was trying to make a simple application in javafx.
I had 8 views (FXML), so one model for each and same for the controllers.
I had to keep the "context" for each model wherever I was... So I had a function setContext which would take a parameter which is a class that regroup every models.
So in every controllers, I had every models.
But a bit latter, I had to had another page, which would take the result of all those page (questionnaire) and show it, so I could have multiple questionnaire... So I was facing the exact same problem, but I didn't want to do it all over again... Because as soon as I'm creating a new questionnaire, I lose the context of the previous one. I also had to add abstractModel and abstractController for stocking every models. It was ratchet.
So I gave up the idea of one controller for each view.
I ended up with a functionnal application, but with one controller which as over 1000 lines... it's only a questionnaire.
I was wondering if there were any possibilities to do what I attempt to do, with multiple controller, but where I don't need to set the "context"? Like... the pages/views auto-save somehow and won't re-instantiate if I'm not asking for it (like a new questionnaire would reset).
Sush as a static class, like a singleton, but for views and which I'm able to instantiate for every questionnaire. But then again, I keep a track on the old ones.
I'm pretty sure it's possible, but can't find anything about it maybe my formulation of the question is just wrong.
Any ideas? Thanks
Your question is bit abstract and it is hard to give a definitive answer. But you might benefit from introducing a dependency injection framework.
One way to do that would be to use Gluon Ignite: "With this library, developers can use popular dependency injection frameworks in their JavaFX applications, including inside their FXML controllers.". You can choose a dependency injection framework you wish from those supported (for example, Dagger, Guice or Spring). With those systems, you can apply scoping rules to your model classes such as Singleton, for those models for which you only wish to have a single instance for your application. You can also use other scoping rules and producers to create models that have different scopes such as within the context of a wizard or created new every time a form is shown, etc.
Beware that using dependency injection frameworks might make your application a little bit more difficult to understand. Anybody maintaining your application has to additionally learn the dependency injection framework. The framework will create objects and inject references to them into your code automatically and your application might be a bit more difficult to debug due to some seemingly magical generated operations that you don't control. Still, it's a tradeoff and, for medium sized applications, the gain in using dependency injection is probably worth it for a lot of apps. From the description you provided, your application may fall into this class, so you should probably seriously consider this approach.
Note that an alternate to a dependency injection system is a service locator (read about it in the Martin Fowler article on dependency injection that I linked earlier). A sample (extremely basic) version of a service locator would be the vista navigator in this small JavaFX navigation framework, though that doesn't pretend to be a full MVC system.
It's just that I can generate multiple questionnaires, which all have the same models and same views and same controllers. But when I create one, it instantiate everything, but it keeps track on all of them so I can edit them later
You could replace your in-memory structure for keeping track of stuff for editing with a persistent storage, for example a JPA based DB access layer or a NoSQL based DB access layer. One advantage of this could also be that the state of the application would be saved if the application is shut down, then restarted, so the user could just pick up where they left off in their questionnaire.

Non-managed objects in Spring application (best practice)

I have been working on a few web applications and REST web services recently (Spring IoC/MVC/Data JPA etc). They usually follow the same pattern: Controller classes --> Service classes (which have several "utility"/business logic classes autowired) --> Spring Data Repositories.
Pretty much all of the classes above are Spring singletons. I feel like this makes the code and some functions within a class dirtier; for example, I can't have a state in a class, I need to pass a lot parameters between methods, and I don't really like having more than 1-2 parameters (although I know sometimes it is necessary).
I was wondering how this problem is overcome in the big (e.g. enterprise) kind of application.
Is it a common practice to use non-Spring managed classes in the Spring application? If so, how do you pass dependencies into it (the ones that would normally be autowired)? If I use constructor injection for example, then I need to autowire all necessary dependencies into the class that creates the object and I wanted to avoid that. Also, I don't really want to be messing with load time weaving etc. to autowire beans into non-Spring objects.
Is using prototype scoped beans a good solution? The only thing is that I need to use AOP's scoped proxies (or method injection etc) to make sure that I get a new instance for any bean that is autowired into a singleton in the first place. Is that a "clean" and reliable option (i.e., is it certain that there will be no concurrency type of issues)? Can I still autowire any singletons into those classes with no issues?
Does anyone that worked on a large system (and actually managed to keep the structure not "bloated" and clean) have any recommendations? Maybe there are some patterns I am not aware and could use?
Any help appreciated.
Spring is well designed, you must not worry about about IoC implementation of DI. The pattern that you have mentioned /Controller Layer -> Service Layer -> Data Access Layer/ is good in practice, and it is ok that these singleton objects does not have state because of rule of OOP: "Think about objects as service providers that does one thing well". Models can have state as JPA units for storing something in Database. Is not mandatory that in large systems you will have dirty code how you mentioned passing a lot of parameters, it just depends on your design decision that will need a deeper construction.

Java, moving from desktop app to web app

I'm going to write my first Java based web app, and I'm sort of lost how to begin.
Firstly, I would like a web app and a desktop app that do pretty much the same thing, without the hackish idea of embedding a web browser into the desktop app because that doesn't allow to easily make changes to the desktop without affecting the web app and vice versa.
Now, here my questions.
Right now, I have a bunch of POJOs and they communicate with a single class that, right now, uses a flat file as a "database", of course, in production, I would use a legitimate database and just change that single class. Is this a good idea? Will I be able to go from POJOs to a web app?
Should I use a framework? I would like to have this app written pretty soon, seeing that all the buisness logic is there, I just need to wrap it so its usable, so, I don't want to spend an extreme amount of time learning, say, Spring (which AFAIK is huge), but, I don't want to keep reinventing the wheel throughout my app either. I can always just use JSP and scriptlets...
If you said yes to the above, what framework(s) do you suggest? Please note that I would like a framework that I can start using in maybe 3-4 weeks of learning.
Will I have to start from scratch with the POJOs that I have written? They're well over 30k LOC, so, if it is like that, I'll be hesitant.
You will need:
a web framework. Since you have Swing background, JSF 2 will be your best bet (everything will be painful, of course, but JSF will get you up and going quickly and will help you avoid the most tragic mistakes). Also, wrapping business pojos into web guis is the main use-case for JSF and it's biggest focus.
a "glue framework". One thing that is much different with web applications as opposed to desktop ones is that you cannot create view components by yourself - they must be created when browser requests a page. So you have to find a way to create the view objects and deliver all the references to the pojos that represent logic, some of which may have very different lifecycles (this is not a problem on desktop, but on web you have to distinguish between pojos that live along with the whole application, along with a single user session, along with a single request, and so on).
The "glue framework" could also provide the additional benefit of managing transactions. You have three choices:
Spring. It's not half as complex as you thing; you only need to learn some basic stuff.
EJB. You would need a real application server, like Glassfish or JBoss
bare JSF has good support for dependency injection, the only drawback is the lack of automatic transaction management.
If I were in your position, I would go with bare JSF 2.0 - this way you only need to learn one new technology. At first, try to avoid libraries like PrimeFaces - they usually work worse than advertised.
edit - and addendum
or - what is "dependency injection"(abridged and simplified)
When request comes to a web application, a new task starts in a new thread (well, the thread is probably recycled, but that's not important).
The application has already been running for some time and most of the objects you are going to need are already built and should not get created again: you have your database connection pool, maybe some parts of business layer; it is also possible that the request is just one of many request made during one session, and you already have a bunch of POJOs that the user is working on. The question is - how to get references to those objects?
You could arrange your application so that resources are available through some static fields. They may be singletons themselves, or they could be acquired through a singleton locator. This tends to work, but is out of fashion (hard to test, hard to refactor, hard to reuse, lifecycles are hard coded in application). The real code could look like this:
public void doSomething() {
Customer Service cs = AppManager.getInstance().getCustomerService();
System.out.println(cs.getVersion());
}
if you need clustering and session management, you could build a special kind of broker that would know and provide to anyone all kinds of needed objects. Each type of object would be registered as a factory under a different name. This also works and is implemented in Java as JNDI. The actual client code would look like this:
public void doSomething() throws Exception {
CustomerService cs = (CustomerService)new InitialContext().lookup("some_fancy_looking_name_in_reality_just_string");
System.out.println(cs.getVersion());
}
The last way is the nicest. Since your initial object is not created by you but by the server just after http request arrives (details depend on the technology you choose, but your entry point might be a JSF managed bean or some kind of action controller), you can just advertise which references you need and let the server take care of finding them for you. This is called "Dependency Injection". Your acts as if everything is taken care of before your code is ever launched. Spring or EJB container, or CDI, or JSF take care of the rest. The code would look like this (just an example):
#EJB
CustomerService cs;
public void doSomething() {
System.out.println(cs.getVersion());
}
Note:
when you use DI, it really uses one of the two former methods under the hood. The good thing is: you do not have to know which one and in some cases you can even switch them without altering your code;
the exact means of registering components for injection differs from framework to framework. It might be a piece of Java code (like in Guice), an XML file (classic Spring) or an annotation (classic EJB 3). Most of the mentioned technologies support different kinds of configuration.
You should definitely use a framework as otherwise sooner or later you'll end up writing your own.
If you use maven then simply typing mvn archetype:generate will give you a huge list of frameworks to choose from and it'll set up all of the scaffolding for you so you can just play with a few frameworks until you find the one that works for you.
Spring has good documentation and is surprisingly easy to get started with. Don't be put off by the pages of documentation! You could use JPA to store stuff in the database. You should (in theory) just be able to annotate your existing POJO's to denote primary keys and so on and it should just work. You can also use JSP's within Spring if that makes life easier.
... I a bunch of POJOs and they communicate with a single class that, right now, uses a flat file as a "database", of course, in production, I would use a legitimate database and just change that single class. Is this a good idea? Will I be able to go from POJOs to a web app?
qualified yes. if the pojo's are sane you should not have many problems. many people use hiberbate.
Should I use a framework? I would like to have this app written pretty soon, seeing that all the buisness logic is there, I just need to wrap it so its usable, so, I don't want to spend an extreme amount of time learning, say, Spring (which AFAIK is huge), but, I don't want to keep reinventing the wheel throughout my app either. I can always just use JSP and scriptlets...
probably. spring is huge, but things like grails or roo can help.
if you want to have a responsive web app, you will need to do some kind of rich client (AJAX). this may require a lot of your code to run on the client. this means writing a lot of javascript or using gwt. this will be a pain. it probably will not be so easy to just "wrap it". if you have written a swing app, then basically that code will need to run on the client.
If you said yes to the above, what framework(s) do you suggest? Please note that I would like a framework that I can start using in maybe 3-4 weeks of learning.
i like groovy and grails - grails uses spring-mvc, spring, hibernate. but there is roo, play and others.
Will I have to start from scratch with the POJOs that I have written? They're well over 30k LOC, so, if it is like that, I'll be hesitant.
the code that will run on the server can probably be mostly left alone. the code that has to run on the client needs to be rewritten in javascript or maybe you can get some reuse out of that code by using gwt,
The Play Framework is doing great things. I would recommend it highly. Having worked with EJB apps and Tomcat/Servlet/Spring apps it's a breath of fresh air. After framework installation you get a working app in a few seconds. Reminds me of Ruby on Rails or Node.js with the type-safety of Java.
Much quicker turnaround on getting started, faster development cycles, and a clearer configuration model than previous Java web app frameworks.
http://www.playframework.com/

JSF2 - backed by EJB or ManagedBean?

As I am learning JSF2, I realized I am not sure what the backing components should be. From design point of view, what is the difference between EJBs and #ManagedBeans?
In the end I am going to use JPA, so EJB is a natural choice for business layer. Is it a good practice to use EJB directly from JSF (as explained here)?
At the moment I'm leaning towards using #ManagedBeans for components which don't need access to business layer (e.g. view helpers) or deal with request/session data. For other purposes, e.g. listing something in a grid, I would directly access EJB.
Is this a good design? Shall I use #ManagedBeans for all backing beans for the sake of clean layer separation, even if in some cases they only delegate to EJB?
Very valid question, but I guess the answer depends on the "strictness" of the approach for your project. There is indeed a bit of redundancy between JSF backing bean and EJB as both implement some business logic.
In a ideal usage of JSF features with converters, rendered, validator, etc. the backing bean could indeed be clean business logic code. But in practice some presentation-related logic frequently leaks in it.
This presentation-related logic should ideally not be in a EJB. This presentation-related logic may depend on the faces package, but not necessary. It's what it does that make it presentation-related or not.
A unified component model has some advantages though. And it's the approach taken by Seam and Spring. In both case, business component with declarative transaction, etc. can be used directly in JSF (Spring does not use EJB but provide a similar model). EJB purist would however say that you should dissociate the two.
So to me it's ultimately a question of taste and size of the project. I can imagine that for a small/medium project using EJB in JSF works fine. For bigger project where this strictness is critical, make sure you don't screw the layers.
In Java EE 6 there is some overlap between the various managed beans: JSF managed beans (#ManagedBean), CDI managed beans (#Named) and EJB beans (#Stateless, #Statefull, #Singleton).
In the view layer I don't see any particular advantage for sticking with #ManagedBean. The CDI variant #Named seems to be able to do the same and more, e.g. provide you with access to the conversion scope.
The current thinking seems to be that eventually the EJB component model will also be retrofitted as a set of CDI annotations. Especially expert group member Reza Rahman frequently hints at this. See e.g. Dependency Injection in Java EE 6 - Part 1
For the time being this has not happened, so EJB beans remain the easiest place to put business logic, especially when JPA is used for persistence.
Nevertheless, whether or not CDI will obtain the capabilities of EJB, IMHO it's still a best practice to use a separate bean for the "backing bean" concept and a separate bean for the "business logic".
The backing bean can be really slim, just containing some references to model objects and services (EJBs). Action Methods of the backing bean can delegate almost directly to the services, but their added value is in providing the user with feedback (adding FacesMessages upon success or failure) and doing small UI modifications (e.g. setting a boolean to false that displayed some dialog).
The Services (business logic) should not know anything about any particular presentation. They should be equally well usable from JSF backing beans, JAX-RS, Servlets, standalone Java SE remote clients or whatever.
Even if all beans would become CDI beans, then this does not change this basic division of responsibility.
Interesting article, didn't knew about that. However, to me this article smells more like a rant towards JSF managed beans. It also tight-couples EJB with JSF. It's maybe interesting in small (personal) applications, but likely not in real world SOA applications where you'd like to have full control over the EJB's been serviced.
As to which one to use for what, I would just stick to #ManagedBean to denote a JSF model --which is tied to one or more specific JSF views. You can perfectly use #EJBs for non-JSF specific business logic and/or datamodels. You can inject #EJBs in a JSF model and delegate it in action methods and maybe also getters/setters, but you should not do the other way round, i.e. do not define the JSF model in an #EJB, this leads to tight coupling and would make #EJBs unuseable outside the JSF context. As far, your design sounds good, as long as you watch to not import anything from javax.faces package in the #EJB class.
By calling EJB from your XHTML, you are introducing tight coupling between the choice of implementation in the view and business tier.
If you use a managed bean to call an EJB, [or even, put in a business delegate], you will be able to change out your business tier completely to Spring without affecting the view layer (XHTML).
Is is technically possible, and very easy for you to (JSR 299) be able to use EJB as your managed bean, and that is probably what these vendors want you to do - get glued to specifics. But whether that is a correct thing to do? - No.

Would you use AOP for database transaction management?

A while back I wrote an application which used Spring AOP for defining which methods were transactional. I am now having second thoughts as to how much of a great idea this was; I have been hit a few times after a minor refactor (changing method signatures etc), which of course doesn't become apparent until something actually goes wrong (and I have a logically inconsistent database).
So I'm interested in a few things:
Have other people decided to revert to explicit transaction management (e.g. via #Transactional annotations)?
Are there useful tools I can use as part of a build process to help identify whether anything has been "broken"?
If people are using AOP to manage transactions, what steps are they taking to avoid the mistakes I've made?
I'm using IntelliJ IDEA which allows you to browse decorated methods and will refactor Spring XML config together with method name changes, but this is not always sufficient (adding a parameter to a method in the wrong place can affect whether an aspect fires for example)
I am currently using declarative transaction management in the two Java projects I work on, specifying which methods need transactional scope with #Transactional annotation. In my opinion, it is a good mix of flexibility and robustness: you are able to see which methods have transactional behavior via a simple text search, can adjust isolation and propagation attributes by hand if needed, and the additional amount of typing is practically negligent.
On one of those projects, I have security/logging implemented via aspects and have occasionally stumbled on same obstacles you when renaming a method or changing signatures. In the worst case, I lost some logging data of user accessing contracts, and in one release, some user roles were not able to access all application features. Nothing major, but, as far as database transactions go, though, I think it's simply not worth it, and I it is better to type #Transactional bit yourself. Spring does the hard part, anyway.
Regarding (1):
I found #Transactonal a more practical solution in all projects worked on in the past few years. In some very specific cases, however, I had also to use Spring AOP to allow the use of more than one JDBC connection / TransactionManager because #Transaction is tied to a single transaction manager.
Regarding (2):
Having said that, in a mixed scenario, I do a lot of automated testing to find possibly broken code. I use Spring's AbstractTransactionalJUnit4SpringContextTests / AbstractTransactionalTestNGSpringContextTests to create my tests. It's been a very effective solution so far.
I tend to be more of a purist, but I try to keep any and all transaction management beyond a simple autocommit, inside the database itself. Most databases are excellent at handling transaction management, after all, its one of the key components of what a database is meant to do.

Categories