Rectangle 27 4

  • You are handling the transaction inside your actionPerformed() method. Its clearly defeating the purpose of DAO/Service layer
  • Your UserService is accepting AbstractDAO, which means some other code may pass wrong DAO implementation to your UserService that will screw things up
  • Most of the time we ain't need all these layers like Service, DAO and BusinessDelegate. So, question yourself are any of these really answering some of your questions. If not, get rid of them. YAGNI
  • Get rid of DAO completely, and treat your Hibernate API as your DAO. Handle database transaction in your business methods. You may like to read this question

After your edit my 3rd suggestion doesn't carry much weight. By the way, you name your DAOs as follows; UserJdbcDAO, UserMysqlDAO etc. Your 2nd name is not making much sense, as we use ORMs just to avoid DB vendor specific DAOs/queries. It might start making some sense if your UserMysqlDAO extends UserJdbcDAO.

@Adeel Ansari: 1- where can i handle transaction? 2- why this is not correct? Specific data operation is into service layer.

@blow: You can handle that in your DAO or Business method. I usually prefer to do it in my business method.

@Adeel Ansari: now my genericDao is like this community.jboss.org/wiki/GenericDataAccessObjects but i have not implemented DaoFactory. Can you write a simple example to show me how and where handle session and transaction? I think do not understand what business-logic means.

@blow: Yes, its likely going to be the same session. But it doesn't look very neat. Now 2nd question, yes, it can be said a business method, precisely.

java - DAO and Service Layer with hibernate - Stack Overflow

java hibernate session transactions dao
Rectangle 27 46

Apart from performing business logic the inefficient way in a managed bean getter method, and using a too broad managed bean scope, it looks okay. If you move the service call from the getter method to a @PostConstruct method and use either @RequestScoped or @ViewScoped instead of @SessionScoped, it will look better.

It's okay. As long as you're consistent with it and the code is readable in a sensible way. Only your way of naming classes and variables is somewhat awkward (illogical and/or duplication). For instance, I personally would use users instead of userList, and use var="user" instead of var="u", and use id and name instead of userId and userName. Also, a "UserListService" sounds like it can only deal with lists of users instead of users in general. I'd rather use "UserService" so you can also use it for creating, updating and deleting users.

It isn't exactly a DAO. Basically, JPA is the real DAO here. Previously, when JPA didn't exist, everyone homegrew DAO interfaces so that the service methods can keep using them even when the underlying implementation ("plain old" JDBC, or "good old" Hibernate, etc) changes. The real task of a service method is transparently managing transactions. This isn't the responsibility of the DAO.

I can imagine that it does that in this relatively simple setup. However, the controller is in fact part of the frontend not the backend. The service is part of the backend which should be designed in such way that it's reusable across all different frontends, such as JSF, JAX-RS, "plain" JSP+Servlet, even Swing, etc. Moreover, the frontend-specific controller (also called "backing bean" or "presenter") allows you to deal in a frontend-specific way with success and/or exceptional outcomes, such as in JSF's case displaying a faces message in case of an exception thrown from a service.

All in all, the correct approach would be like below:

<h:dataTable value="#{userBacking.users}" var="user">
    <h:column>#{user.id}</h:column>
    <h:column>#{user.name}</h:column>
</h:dataTable>
@Named
@RequestScoped // Use @ViewScoped once you bring in ajax (e.g. CRUD)
public class UserBacking {

    private List<User> users;

    @EJB
    private UserService userService;

    @PostConstruct
    public void init() {
        users = userService.listAll();
    }

    public List<User> getUsers() {
        return users;
    }

}
@Stateless
public class UserService {

    @PersistenceContext
    private EntityManager em;

    public List<User> listAll() {
        return em.createQuery("SELECT u FROM User u", User.class).getResultList();
    }

}

You can find here a real world kickoff project here utilizing the canonical Java EE / JSF / CDI / EJB / JPA practices: Java EE kickoff app.

"JPA is the real DAO here" gives my brain a deep impact to understand this statement. :) Is it anything that provides an abstraction to some kind of persistence mechanism like a DB and allows retrieval and persistence of domain objects to and from the DB without exposing the internal details of the underlying DB is said to be a DAO? This is somewhat confusing as compared to older questions/answers/blogs/tutorials/articles somewhere else.

@LyK: You shouldn't cache DB results in all sessions in the frontend. You should cache them in a single place in the backend. JPA offers 2nd level cache possibility. Additional advantage, it knows precisely when to invalidate a cached entity.

java ee - JSF Controller, Service and DAO - Stack Overflow

jsf java-ee jpa ejb dao
Rectangle 27 46

Apart from performing business logic the inefficient way in a managed bean getter method, and using a too broad managed bean scope, it looks okay. If you move the service call from the getter method to a @PostConstruct method and use either @RequestScoped or @ViewScoped instead of @SessionScoped, it will look better.

It's okay. As long as you're consistent with it and the code is readable in a sensible way. Only your way of naming classes and variables is somewhat awkward (illogical and/or duplication). For instance, I personally would use users instead of userList, and use var="user" instead of var="u", and use id and name instead of userId and userName. Also, a "UserListService" sounds like it can only deal with lists of users instead of users in general. I'd rather use "UserService" so you can also use it for creating, updating and deleting users.

It isn't exactly a DAO. Basically, JPA is the real DAO here. Previously, when JPA didn't exist, everyone homegrew DAO interfaces so that the service methods can keep using them even when the underlying implementation ("plain old" JDBC, or "good old" Hibernate, etc) changes. The real task of a service method is transparently managing transactions. This isn't the responsibility of the DAO.

I can imagine that it does that in this relatively simple setup. However, the controller is in fact part of the frontend not the backend. The service is part of the backend which should be designed in such way that it's reusable across all different frontends, such as JSF, JAX-RS, "plain" JSP+Servlet, even Swing, etc. Moreover, the frontend-specific controller (also called "backing bean" or "presenter") allows you to deal in a frontend-specific way with success and/or exceptional outcomes, such as in JSF's case displaying a faces message in case of an exception thrown from a service.

All in all, the correct approach would be like below:

<h:dataTable value="#{userBacking.users}" var="user">
    <h:column>#{user.id}</h:column>
    <h:column>#{user.name}</h:column>
</h:dataTable>
@Named
@RequestScoped // Use @ViewScoped once you bring in ajax (e.g. CRUD)
public class UserBacking {

    private List<User> users;

    @EJB
    private UserService userService;

    @PostConstruct
    public void init() {
        users = userService.listAll();
    }

    public List<User> getUsers() {
        return users;
    }

}
@Stateless
public class UserService {

    @PersistenceContext
    private EntityManager em;

    public List<User> listAll() {
        return em.createQuery("SELECT u FROM User u", User.class).getResultList();
    }

}

You can find here a real world kickoff project here utilizing the canonical Java EE / JSF / CDI / EJB / JPA practices: Java EE kickoff app.

"JPA is the real DAO here" gives my brain a deep impact to understand this statement. :) Is it anything that provides an abstraction to some kind of persistence mechanism like a DB and allows retrieval and persistence of domain objects to and from the DB without exposing the internal details of the underlying DB is said to be a DAO? This is somewhat confusing as compared to older questions/answers/blogs/tutorials/articles somewhere else.

@LyK: You shouldn't cache DB results in all sessions in the frontend. You should cache them in a single place in the backend. JPA offers 2nd level cache possibility. Additional advantage, it knows precisely when to invalidate a cached entity.

java ee - JSF Controller, Service and DAO - Stack Overflow

jsf java-ee jpa ejb dao
Rectangle 27 46

Apart from performing business logic the inefficient way in a managed bean getter method, and using a too broad managed bean scope, it looks okay. If you move the service call from the getter method to a @PostConstruct method and use either @RequestScoped or @ViewScoped instead of @SessionScoped, it will look better.

It's okay. As long as you're consistent with it and the code is readable in a sensible way. Only your way of naming classes and variables is somewhat awkward (illogical and/or duplication). For instance, I personally would use users instead of userList, and use var="user" instead of var="u", and use id and name instead of userId and userName. Also, a "UserListService" sounds like it can only deal with lists of users instead of users in general. I'd rather use "UserService" so you can also use it for creating, updating and deleting users.

It isn't exactly a DAO. Basically, JPA is the real DAO here. Previously, when JPA didn't exist, everyone homegrew DAO interfaces so that the service methods can keep using them even when the underlying implementation ("plain old" JDBC, or "good old" Hibernate, etc) changes. The real task of a service method is transparently managing transactions. This isn't the responsibility of the DAO.

I can imagine that it does that in this relatively simple setup. However, the controller is in fact part of the frontend not the backend. The service is part of the backend which should be designed in such way that it's reusable across all different frontends, such as JSF, JAX-RS, "plain" JSP+Servlet, even Swing, etc. Moreover, the frontend-specific controller (also called "backing bean" or "presenter") allows you to deal in a frontend-specific way with success and/or exceptional outcomes, such as in JSF's case displaying a faces message in case of an exception thrown from a service.

All in all, the correct approach would be like below:

<h:dataTable value="#{userBacking.users}" var="user">
    <h:column>#{user.id}</h:column>
    <h:column>#{user.name}</h:column>
</h:dataTable>
@Named
@RequestScoped // Use @ViewScoped once you bring in ajax (e.g. CRUD)
public class UserBacking {

    private List<User> users;

    @EJB
    private UserService userService;

    @PostConstruct
    public void init() {
        users = userService.listAll();
    }

    public List<User> getUsers() {
        return users;
    }

}
@Stateless
public class UserService {

    @PersistenceContext
    private EntityManager em;

    public List<User> listAll() {
        return em.createQuery("SELECT u FROM User u", User.class).getResultList();
    }

}

You can find here a real world kickoff project here utilizing the canonical Java EE / JSF / CDI / EJB / JPA practices: Java EE kickoff app.

"JPA is the real DAO here" gives my brain a deep impact to understand this statement. :) Is it anything that provides an abstraction to some kind of persistence mechanism like a DB and allows retrieval and persistence of domain objects to and from the DB without exposing the internal details of the underlying DB is said to be a DAO? This is somewhat confusing as compared to older questions/answers/blogs/tutorials/articles somewhere else.

@LyK: You shouldn't cache DB results in all sessions in the frontend. You should cache them in a single place in the backend. JPA offers 2nd level cache possibility. Additional advantage, it knows precisely when to invalidate a cached entity.

java ee - JSF Controller, Service and DAO - Stack Overflow

jsf java-ee jpa ejb dao
Rectangle 27 43

Apart from performing business logic the inefficient way in a managed bean getter method, and using a too broad managed bean scope, it looks okay. If you move the service call from the getter method to a @PostConstruct method and use either @RequestScoped or @ViewScoped instead of @SessionScoped, it will look better.

It's okay. As long as you're consistent with it and the code is readable in a sensible way. Only your way of naming classes and variables is somewhat awkward (illogical and/or duplication). For instance, I personally would use users instead of userList, and use var="user" instead of var="u", and use id and name instead of userId and userName. Also, a "UserListService" sounds like it can only deal with lists of users instead of users in general. I'd rather use "UserService" so you can also use it for creating, updating and deleting users.

It isn't exactly a DAO. Basically, JPA is the real DAO here. Previously, when JPA didn't exist, everyone homegrew DAO interfaces so that the service methods can keep using them even when the underlying implementation ("plain old" JDBC, or "good old" Hibernate, etc) changes. The real task of a service method is transparently managing transactions. This isn't the responsibility of the DAO.

I can imagine that it does that in this relatively simple setup. However, the controller is in fact part of the frontend not the backend. The service is part of the backend which should be designed in such way that it's reusable across all different frontends, such as JSF, JAX-RS, "plain" JSP+Servlet, even Swing, etc. Moreover, the frontend-specific controller (also called "backing bean" or "presenter") allows you to deal in a frontend-specific way with success and/or exceptional outcomes, such as in JSF's case displaying a faces message in case of an exception thrown from a service.

All in all, the correct approach would be like below:

<h:dataTable value="#{userBacking.users}" var="user">
    <h:column>#{user.id}</h:column>
    <h:column>#{user.name}</h:column>
</h:dataTable>
@Named
@RequestScoped // Use @ViewScoped once you bring in ajax (e.g. CRUD)
public class UserBacking {

    private List<User> users;

    @EJB
    private UserService userService;

    @PostConstruct
    public void init() {
        users = userService.listAll();
    }

    public List<User> getUsers() {
        return users;
    }

}
@Stateless
public class UserService {

    @PersistenceContext
    private EntityManager em;

    public List<User> listAll() {
        return em.createQuery("SELECT u FROM User u", User.class).getResultList();
    }

}

You can find here a real world kickoff project here utilizing the canonical Java EE / JSF / CDI / EJB / JPA practices: Java EE kickoff app.

"JPA is the real DAO here" gives my brain a deep impact to understand this statement. :) Is it anything that provides an abstraction to some kind of persistence mechanism like a DB and allows retrieval and persistence of domain objects to and from the DB without exposing the internal details of the underlying DB is said to be a DAO? This is somewhat confusing as compared to older questions/answers/blogs/tutorials/articles somewhere else.

@LyK: You shouldn't cache DB results in all sessions in the frontend. You should cache them in a single place in the backend. JPA offers 2nd level cache possibility. Additional advantage, it knows precisely when to invalidate a cached entity.

java ee - JSF Controller, Service and DAO - Stack Overflow

jsf java-ee jpa ejb dao
Rectangle 27 43

Apart from performing business logic the inefficient way in a managed bean getter method, and using a too broad managed bean scope, it looks okay. If you move the service call from the getter method to a @PostConstruct method and use either @RequestScoped or @ViewScoped instead of @SessionScoped, it will look better.

It's okay. As long as you're consistent with it and the code is readable in a sensible way. Only your way of naming classes and variables is somewhat awkward (illogical and/or duplication). For instance, I personally would use users instead of userList, and use var="user" instead of var="u", and use id and name instead of userId and userName. Also, a "UserListService" sounds like it can only deal with lists of users instead of users in general. I'd rather use "UserService" so you can also use it for creating, updating and deleting users.

It isn't exactly a DAO. Basically, JPA is the real DAO here. Previously, when JPA didn't exist, everyone homegrew DAO interfaces so that the service methods can keep using them even when the underlying implementation ("plain old" JDBC, or "good old" Hibernate, etc) changes. The real task of a service method is transparently managing transactions. This isn't the responsibility of the DAO.

I can imagine that it does that in this relatively simple setup. However, the controller is in fact part of the frontend not the backend. The service is part of the backend which should be designed in such way that it's reusable across all different frontends, such as JSF, JAX-RS, "plain" JSP+Servlet, even Swing, etc. Moreover, the frontend-specific controller (also called "backing bean" or "presenter") allows you to deal in a frontend-specific way with success and/or exceptional outcomes, such as in JSF's case displaying a faces message in case of an exception thrown from a service.

All in all, the correct approach would be like below:

<h:dataTable value="#{userBacking.users}" var="user">
    <h:column>#{user.id}</h:column>
    <h:column>#{user.name}</h:column>
</h:dataTable>
@Named
@RequestScoped // Use @ViewScoped once you bring in ajax (e.g. CRUD)
public class UserBacking {

    private List<User> users;

    @EJB
    private UserService userService;

    @PostConstruct
    public void init() {
        users = userService.listAll();
    }

    public List<User> getUsers() {
        return users;
    }

}
@Stateless
public class UserService {

    @PersistenceContext
    private EntityManager em;

    public List<User> listAll() {
        return em.createQuery("SELECT u FROM User u", User.class).getResultList();
    }

}

You can find here a real world kickoff project here utilizing the canonical Java EE / JSF / CDI / EJB / JPA practices: Java EE kickoff app.

"JPA is the real DAO here" gives my brain a deep impact to understand this statement. :) Is it anything that provides an abstraction to some kind of persistence mechanism like a DB and allows retrieval and persistence of domain objects to and from the DB without exposing the internal details of the underlying DB is said to be a DAO? This is somewhat confusing as compared to older questions/answers/blogs/tutorials/articles somewhere else.

@LyK: You shouldn't cache DB results in all sessions in the frontend. You should cache them in a single place in the backend. JPA offers 2nd level cache possibility. Additional advantage, it knows precisely when to invalidate a cached entity.

java ee - JSF Controller, Service and DAO - Stack Overflow

jsf java-ee jpa ejb dao
Rectangle 27 43

Apart from performing business logic the inefficient way in a managed bean getter method, and using a too broad managed bean scope, it looks okay. If you move the service call from the getter method to a @PostConstruct method and use either @RequestScoped or @ViewScoped instead of @SessionScoped, it will look better.

It's okay. As long as you're consistent with it and the code is readable in a sensible way. Only your way of naming classes and variables is somewhat awkward (illogical and/or duplication). For instance, I personally would use users instead of userList, and use var="user" instead of var="u", and use id and name instead of userId and userName. Also, a "UserListService" sounds like it can only deal with lists of users instead of users in general. I'd rather use "UserService" so you can also use it for creating, updating and deleting users.

It isn't exactly a DAO. Basically, JPA is the real DAO here. Previously, when JPA didn't exist, everyone homegrew DAO interfaces so that the service methods can keep using them even when the underlying implementation ("plain old" JDBC, or "good old" Hibernate, etc) changes. The real task of a service method is transparently managing transactions. This isn't the responsibility of the DAO.

I can imagine that it does that in this relatively simple setup. However, the controller is in fact part of the frontend not the backend. The service is part of the backend which should be designed in such way that it's reusable across all different frontends, such as JSF, JAX-RS, "plain" JSP+Servlet, even Swing, etc. Moreover, the frontend-specific controller (also called "backing bean" or "presenter") allows you to deal in a frontend-specific way with success and/or exceptional outcomes, such as in JSF's case displaying a faces message in case of an exception thrown from a service.

All in all, the correct approach would be like below:

<h:dataTable value="#{userBacking.users}" var="user">
    <h:column>#{user.id}</h:column>
    <h:column>#{user.name}</h:column>
</h:dataTable>
@Named
@RequestScoped // Use @ViewScoped once you bring in ajax (e.g. CRUD)
public class UserBacking {

    private List<User> users;

    @EJB
    private UserService userService;

    @PostConstruct
    public void init() {
        users = userService.listAll();
    }

    public List<User> getUsers() {
        return users;
    }

}
@Stateless
public class UserService {

    @PersistenceContext
    private EntityManager em;

    public List<User> listAll() {
        return em.createQuery("SELECT u FROM User u", User.class).getResultList();
    }

}

You can find here a real world kickoff project here utilizing the canonical Java EE / JSF / CDI / EJB / JPA practices: Java EE kickoff app.

"JPA is the real DAO here" gives my brain a deep impact to understand this statement. :) Is it anything that provides an abstraction to some kind of persistence mechanism like a DB and allows retrieval and persistence of domain objects to and from the DB without exposing the internal details of the underlying DB is said to be a DAO? This is somewhat confusing as compared to older questions/answers/blogs/tutorials/articles somewhere else.

@LyK: You shouldn't cache DB results in all sessions in the frontend. You should cache them in a single place in the backend. JPA offers 2nd level cache possibility. Additional advantage, it knows precisely when to invalidate a cached entity.

java ee - JSF Controller, Service and DAO - Stack Overflow

jsf java-ee jpa ejb dao
Rectangle 27 2

Use interfaces for dependencies that expose an API of some sort and that have an implementation that may need to be swapped out (e.g. using mocks in unit tests). One common case is the DAO (data access object), which in Spring Data refers to as a Repository, which ties your data model to a persistence layer. Another common case is a Service which exposes operations on your domain model. Typically a Service will depend on the data access layer, so to unit test the service you will mock the DAO/repository. Another example is a third-party service; these are often only used by production systems, but must be simulated in development and testing environments. In this case, an interface is far superior to, say, embedding boolean flags in your code and hoping you don't have any logic errors.

The key thing to remember about managing dependencies is actually managing your use of the new keyword. Any time you use new, you are creating a dependency on an implementation. The goal of dependency injection is to separate how you use things you depend on with how you get them. You can depend on either an interface or a class, for a simple, obvious reason: Java supports subclassing. So even if you depend on a class instead of an interface, you might end up with a subclass. Spring framework actually does this automatically in many cases.

If you find yourself needing to create objects and you're not sure that you should depend on them, have your dependency injection framework give you a Factory for those objects. How this works is obviously framework-dependent, but all frameworks that I know of support factories. If you're not using a framework, you can still write factories and use them instead of using new all the time.

java - Spring Dependency Injection usage - Stack Overflow

java spring dependency-injection
Rectangle 27 2

You should consolidate your JPA access into a DAO or service layer of one kind or another, if for no other reason you can then stub out that DAO layer for unit tests. All of your JSF managed beans would then route their JPA access through that class. That way, whenever you access JPA from your JSF managed beans, you can mock the single DAO method call rather than mocking EntityManager, Query, etc. individually.

Now, the harder question: should that DAO/service layer be another JSF managed bean, an EJB or something else altogether? That's in some sense less important than acknowledging that you want to separate JPA access.

Personally, I started out making DAOs as just another flavor of JSF managed beans using @ManagedProperty for injection. Then I discovered CDI in Java EE 6 and made them POJOs with @Named/@Inject instead.

If you are doing writes and not just reads, though, you should consider having a separate service layer on which you can declare transactions - probably @Stateless EJBs make the most sense if you're using JSF.

also - I had written this a while back, before I got into CDI. You might find it useful, although your mileage may vary and it might already be outdated. wrschneider.blogspot.com/2011/09/

So you are saying that the CRUD (and other methods) for every entity should be placed in a separate class right? In this case I don't understand why would I need this DAO layer.

java - Integrate JSF with JPA - Stack Overflow

java jsf jpa
Rectangle 27 3

Just a little note first: usually in an application organized in layers like Presentation / Service / DAO for example, you have the following rules:

  • Each layer knows only the layer immediately below.
  • It knows it only by it's interfaces, and not by it's implementation class.

This will provide easier testing, a better code encapsulation, and a sharper definition of the different layers (through interfaces that are easily identified as public API)

That said, there is a very common way to handle that kind of situation in a way that allow the most flexibility: dependency injection. And Spring is the industry standard implementation of dependency injection (and of a lot of other things)

The idea (in short) is that your service will know that it needs a IEntityDAO, and that someone will inject in it and implementation of the interface before actually using the service. That someone is called an IOC container (Inversion of Control container). It can be Spring, and what it does is usually described by an application configuration file and will be done at application startup.

Important Note: The concept is brilliant and powerful but dead simple stupid. You can also use the Inversion of Control architectural pattern without a framework with a very simple implementation consisting in a large static method "assembling" your application parts. But in an industrial context it's better to have a framework which will allow to inject other things like database connection, web service stub clients, JMS queues, etc...

  • Your have an easy time mocking and testing, as the only thing a class depends on is interfaces
  • You have a single file of a small set of XML files that describe the whole structure of your application, which is really handy when your application grows.
  • It's a very widely adopted standard and well - known by many java developers.
public abstract class AbstractService<IEntityDAO> {

    private IEntityDAO entityDAO; // you don't know the concrete implementation, maybe it's a mock for testing purpose

    public AbstractService() {
    }

    protected EntityDAO getEntityDAO() { // only subclasses need this method
    }

    public void setEntityDAO(IEntityDAO dao) { // IOC container will call this method
        this.entityDAO = dao;
    }
}

And in spring configuration file, you will have something like that:

<bean id="ProductDAO" class="com.company.dao.ProductDAO" />

[...]

<bean id="ProductService" class="com.company.service.ProductService">
    <property name="entityDAO" ref="ProductDAO"/>
</bean>

CDI is a bit more of a standard nowadays. EE 6 has changed much.

Thanks for the answer, it looks really good. Unfortunatly this is for some school project. It's not really relevant to the question, and the guy I work with already knows Spring. He asked the teacher if we could use it but he said no (cause we haven't handled it in lessons yet). I think I'll just keep them loosely coupled, then :) and assign the dao object in each service's constructor.

@MarioDeSchaepmeester Welcome to the real world. Sometimes for good or bad reasons you cannot take advantage of a framework or a library, but like I said in the "Important Note", you don't need spring to implement IOC. Actually if you just have a couple of classes using Spring would just be a waste of time. You can just set up your classes and layers, and pro grammatically instantiate them and link them together with setEntityDAO()-like methods. But probably IOC will be one of your courses later... Otherwise make sure to learn it on your own because it's a very important concept.

@SamuelRossille I'm afraid that hoping to still see IOC this year would be too optimistic. I cannot begin to explain how shallow the courses are that my school gives, and I feel really disappointed. This is my last year and lessons are finished in January, with a project and an internship following. Good thing there's Stack Overflow and people like you to help me learn the important stuff. Would you think CDI is a good way to go from here? I found a source that looks good

@MarioDeSchaepmeester That might be sad, but if you plan to make a career in software edition you will have to learn a lot on your own all the time anyways. I don't know CDI, I just discovered it thanks to atamanroman's comment, so I can't give advice about it. However it's never a bad thing to read about something.

oop - Advice wanted on a complex structure in java (DAO and Service La...

java oop design-patterns design generics
Rectangle 27 3

Just a little note first: usually in an application organized in layers like Presentation / Service / DAO for example, you have the following rules:

  • Each layer knows only the layer immediately below.
  • It knows it only by it's interfaces, and not by it's implementation class.

This will provide easier testing, a better code encapsulation, and a sharper definition of the different layers (through interfaces that are easily identified as public API)

That said, there is a very common way to handle that kind of situation in a way that allow the most flexibility: dependency injection. And Spring is the industry standard implementation of dependency injection (and of a lot of other things)

The idea (in short) is that your service will know that it needs a IEntityDAO, and that someone will inject in it and implementation of the interface before actually using the service. That someone is called an IOC container (Inversion of Control container). It can be Spring, and what it does is usually described by an application configuration file and will be done at application startup.

Important Note: The concept is brilliant and powerful but dead simple stupid. You can also use the Inversion of Control architectural pattern without a framework with a very simple implementation consisting in a large static method "assembling" your application parts. But in an industrial context it's better to have a framework which will allow to inject other things like database connection, web service stub clients, JMS queues, etc...

  • Your have an easy time mocking and testing, as the only thing a class depends on is interfaces
  • You have a single file of a small set of XML files that describe the whole structure of your application, which is really handy when your application grows.
  • It's a very widely adopted standard and well - known by many java developers.
public abstract class AbstractService<IEntityDAO> {

    private IEntityDAO entityDAO; // you don't know the concrete implementation, maybe it's a mock for testing purpose

    public AbstractService() {
    }

    protected EntityDAO getEntityDAO() { // only subclasses need this method
    }

    public void setEntityDAO(IEntityDAO dao) { // IOC container will call this method
        this.entityDAO = dao;
    }
}

And in spring configuration file, you will have something like that:

<bean id="ProductDAO" class="com.company.dao.ProductDAO" />

[...]

<bean id="ProductService" class="com.company.service.ProductService">
    <property name="entityDAO" ref="ProductDAO"/>
</bean>

CDI is a bit more of a standard nowadays. EE 6 has changed much.

Thanks for the answer, it looks really good. Unfortunatly this is for some school project. It's not really relevant to the question, and the guy I work with already knows Spring. He asked the teacher if we could use it but he said no (cause we haven't handled it in lessons yet). I think I'll just keep them loosely coupled, then :) and assign the dao object in each service's constructor.

@MarioDeSchaepmeester Welcome to the real world. Sometimes for good or bad reasons you cannot take advantage of a framework or a library, but like I said in the "Important Note", you don't need spring to implement IOC. Actually if you just have a couple of classes using Spring would just be a waste of time. You can just set up your classes and layers, and pro grammatically instantiate them and link them together with setEntityDAO()-like methods. But probably IOC will be one of your courses later... Otherwise make sure to learn it on your own because it's a very important concept.

@SamuelRossille I'm afraid that hoping to still see IOC this year would be too optimistic. I cannot begin to explain how shallow the courses are that my school gives, and I feel really disappointed. This is my last year and lessons are finished in January, with a project and an internship following. Good thing there's Stack Overflow and people like you to help me learn the important stuff. Would you think CDI is a good way to go from here? I found a source that looks good

@MarioDeSchaepmeester That might be sad, but if you plan to make a career in software edition you will have to learn a lot on your own all the time anyways. I don't know CDI, I just discovered it thanks to atamanroman's comment, so I can't give advice about it. However it's never a bad thing to read about something.

oop - Advice wanted on a complex structure in java (DAO and Service La...

java oop design-patterns design generics
Rectangle 27 0

Annotate your controller with @Transactional (or maybe some service if it is an intermediate between your controller and DAO). Service is actually a better place, otherwise you need to place <tx:annotation-driven /> in *-servlet.xml MVC configuration file as well.

I have never used this library (I personally use Spring Data JPA from Spring portfolio), but the documentation doesn't say anything about transactions, so I guess it is up to the user to configure them.

UPDATE: looking at the examples they provide seems like I am right:

@Transactional
public class CitizenServiceImpl implements CitizenService {
//...

Hey, thanks a lot. Been struggling with this for the whole day.

java - No Hibernate Session bound to thread with generic-hibernate-dao...

java hibernate spring spring-mvc hibernate-session