What is the difference between DAO and Spring Beans? - java

I'm starting to program in Java (with the Spring Framework) and finding myself confused about the difference between DAOs and Spring's Beans. Do they serve to the same purpose?

DAO == Data Access Object. It's one way to write a persistence layer.
Spring can manage DAO beans and lots of other kinds, like message-driven beans, services, web controllers, and anything else you can encapsulate into a bean.
Spring has three parts:
Inversion of Control (IOC). Think of Spring as a big factory for creating and managing beans.
Aspect-oriented programming (AOP). This is how Spring manages cross cutting concerns like logging, transactions, proxying, remoting, and other activities that otherwise would be littered throughout your application.
Framework code, like the persistence templates for JDBC, Hibernate, TopLink, etc.; remoting; web MVC; etc. They write better code than we do - you get to just use it.

DAOs are a pattern concept (http://www.oracle.com/technetwork/java/dataaccessobject-138824.html).
Spring Beans are class instances managed by Spring.
Of course you can use Spring IOC to implement an application using DAOs.

DAOs are meant to abstract away how the application constructs a data object. More specifically, you can have an interface UserDAO and implement it as a UserHibernateDAO, UserIbatisDAO, UserFileDAO and have them return data in a single format from different sources.
Duffymo explained Spring.

Related

spring vs ejb3 - what is different in beans injection?

is it correct that in spring I can inject my own beans , and in ejb3 I can inject only ejb3 beans ? if so how can ejb3 be a replacement to Spring?
Besides the fact that you can use CDI for injecting different types of beans, what do you mean by "ejb3" beans and how those beans are not yours as in case of spring? Spring injects any kind of bean and you do that either by declaring it in XML (old approach) or by specifying an annotation (#Component, #Service, etc.). Which is the case also for EJB3 (you can use #Stateless instead of #Service, just to make an analogy).
So, in JEE environment one can be replaced with the other (from this point of view, Spring has some advantages as it sets the grounds for fast development, providing additional helpers, libraries, frameworks on top of JEE specification - see Spring Data JPA for one).
So, I think is a matter of how you design your application to use one or the other.
In a Java EE environment, you can not only use EJB, but also CDI.
see How do CDI and EJB compare? interact?

Should repository layer always be encapsulated by a service layer?

In the repository layer I define normal data operations such as inserting, finding and so on. I am using Spring and I have the #Repository annotation above the class. Is it bad to use this class directly in the #Controller class for instance? Should all repositories always have a service layer that just delegate to the repository layer?
It totally depends on your choice. In Spring Roo, you don't just skip the Repository or Service layer, but use a Rich Domain Model where you have the data access logic in the domain itself. Frameworks like Groovy on Grails use a single Repository layer. So i think its OK to use it directly in the Controller.
I similarly asked what use are EJBs? An answer said this:
your [service layer] typically orchestrates application of business logic but more often than not does not actually perform it, it is usually a very thin wrapper.
The service-layer methods can define the operations that are transactions, and which therefore have annotations to get AOP transaction support added automatically for you. See also an answer to a related question, which says:
Spring's idiom would recommend having a service interface that knows about units of work and a persistence interface that deals with relational databases. The methods in the service interface should map closely to your use cases. The service implementation knows about all the model and persistence packages and classes it needs to accomplish the goals of the use case.

CDI and EJB, security issues?

I am reviewing my code from since I picked up on JSF.
One of the most complex issues has come up once again. The decision between CDI and EJB.
I am using three layers and I wonder which type of annotation to use on each of them:
- Backing beans (the Controller as defined in MVC)
- The service layer
- DAO's
My backing beans are using CDI, as long as I don't need anything from EJB.
But I am stuck on those other two. I remember reading about using EJB beans because of the pooling functionalities, which would prevent massive loads of requests (or attacks, if you will).
So in short, is there ANY reason to use EJB (Stateless, Stateful, LocalBean et cetera), considering security or anything else (excluded ViewScoped)?
Thanks in advance.
You're making a conceptual mistake here. CDI is absolutely not an alternative to EJB. CDI in its default trim doesn't offer transaction management at all. CDI is a bean management and dependency injection API, not a service layer API. In order to manage transactions in CDI, you've to add another API along with a bunch of another annotations.
CDI can replace for example JSF managed bean annotations, but definitely not EJB annotations.
So there's no means of a valid "CDI vs EJB" question. Both have their own completely distinct purposes. Note that you can perfectly inject EJB based service classes in CDI based managed bean classes.
As to security, it's not clear why you mentioned that part in the title and the tags, but the decision between CDI and EJB has nothing to do with security (simply because there's no means of a valid "CDI vs EJB" question in first place).
Yes when you require out-of-box support for transactions, concurrency, pooling etc.

Porting my hibernate Dao layer in a stand-alone java app?

I have a spring mvc application that I am using Hibernate with.
I am using the sessionFactory.getCurrentSession in my Dao methods (not hibernate support).
What I want to know is, what do I have to do to be able to use my hibernate database layer
in a non-web application?
I have a stand-alone java application (that runs via main) where I load spring's application context
programatically and then get my service layer (which depends on my hibernate db layer).
Do I need to do anything special in my spring.xml file to setup hibernate's session?
In my spring mvc web app, I did annotate my Dao methods with the #Transactional annotation.
(I want the transaction on a per call basis, not for a group of db calls).
P.S In my web app, how are sessions created/destroyed, is it per request?
You can get hold of the spring ApplicationContext from main method. it will behave exactly the same as the one in web.
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
YourDAO yDao = (YourDAO)context.getBean("yourDAO");
yDao.callYourSpecialMethod();
So, from this point there is no dependancy for hibernate, it should work automatically. here just the view gets changed, no logical or structural changes. So the transactions and other things should work as usual.

Adding rest service to a struts application

I'm trying to add rest services to a struts application using jersey.For this i need to segregate the java code in such a way that it can be commonly accessed by both the struts and rest api.This is done so that the code is shared between both rest and struts,and any change will reflect in both the services.I would like to know , how much of this idea is feasible and weather this is how usually people design rest services .
While our presentation layer isn't Struts based (usually it's either Spring Web MVC or JSF), we use Spring 3.0 + Java EE 6, specifically, EJB 3.0 and JPA 2.0 for such situations.
EJB 3.0 stateless session beans work great—they can have declarative (annotation-based) dependency injection and transaction demarcation, or they can manage their transactions, dependencies and resources themselves using whatever traditional mechanism. They seamless integrate with JPA 2.0 and are easy enough to unit test. The main advantage over pure Spring beans is that they can be deployed independently of the Web application (as an EJB JAR).
On the front-facing Web services, we also use Jersey/JAX-RS. Because Jersey/JAX-RS dependency injection is broken (it doesn't use Weld/CDI like the rest of Java EE), we've had to resort to Spring DI to 'wire' up the front-facing REST resource classes with the 'back-end' EJBs. The good thing is this works well enough to inject the EJBs into our MVC controllers and can also be used with JSF managed beans. Alternatively, you can write your REST-ful resources using Spring alone (either way has its own pros/cons, but in general both do the job well).
I know I glossed over the whole thing but I'd be glad to share more details upon request.
EDIT: Some more details, as per request.
You're first stop for learning Jersey/JAX-RS would have to be the Jersey User Guide. There are also several tutorials/examples you can easily find across the 'Net.
While you should be able to package Jersey/JAX-RS resources into the same WAR as your Struts pages, we went with the simpler alternative of deploying them separately.
Now, when deploying to Glassfish 3.1, we hit this bug, also documented here. The bottom line is that #EJB injection didn't work for us as expected.
So, instead, we fell back on to Spring using the jersey-spring contrib module, following this example.
Anyway, the rest of it is standard Java EE 6 / EJB 3.0. We identify and place all common functionality into a 'service' layer which are largely implemented as #Stateless EJBs.
Persistence is handled through JPA #Entitys accessed through a JPA inject EntityManager. Transactions are declaratively demarcated using #TransactionAttribute.
Here's a quick illustration of a typical EJB + JPA service bean:
#Stateless
public class WidgetServiceBean implements WidgetService {
#PersistenceContext
private EntityManager em;
#Override
public List<Widget> findWidgetByName(String name) {
return em.createNamedQuery("Widget.findByName", Widget.class)
.setParam("name", name).getResultList();
}
#Override
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public void removeWidgetById(int id) {
em.find(Widget.class, id).remove();
}
}
(Obviously not production quality but just shows how 'lean' they can be.)
The service layer and entities are packaged as an EJB JAR which can be deployed separately, and made available to all other modules via global JNDI lookup. Or, they can be deployed within the Struts or JAX-RS WAR and as of Java EE 6 (Glassfish 3.x) they will be found, deployed as part of the module and made available to other components within the same WAR.
Some might argue that it's simpler to just use Spring beans if you're using the Spring container anyway. I would say, probably, but then you also have to use Spring's persistence framework, and Spring's transaction framework. (Spring also provides declarative transactions and persistence.) If you're already heavily invested into Spring then that might be an easier path.
OTOH, EJB 3.0, JPA 2.0 and JTA have also been radically simplified from their predecessors and are part of the Java EE standard so it's an architectural decision with a lot of dimensions.

Categories