/
Services and DAO(Data Access Object)

Services and DAO(Data Access Object)

Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @RestController class file.

 

To call the service from @RestController :

public class ProductController { ProductService productService; }

 

You can create an Interface like :

public interface ProductService { }

 

The following code will let you to create a class which implements the ProductService interface with @Service annotation and write the business logic.

public class ProductServiceImpl implements ProductService { private ProductDao productdao; }

 

A particular advantage of using interface in Java is that it allows multiple inheritance.we can achieve the security etc.

The service layer operate on the data sent to and from the DAO and the client.

 

DAO(Data Access Object) :

DAO layer used to provide a connection to the DB.Following are the participants in Data Access Object Pattern:

  • Data Access Object Interface :

    • This interface defines the standard operations to be performed on a model object(s).

  • Data Access Object concrete class :

    • This class implements above interface. This class is responsible to get data from a data source which can be database / xml or any other storage mechanism.

  • Model Object or Value Object :

    • This object is simple POJO containing get/set methods to store data retrieved using DAO class.

 

Create Data Access Object Interface.

public interface ProductDao { }

 

Create concrete class implementing above interface.

public class ProductDaoImpl implements ProductDao { @Override function fetch(int productID){ Session session = HibernateUtil.getHibernateSession(); HibernateUtil.beginTransaction(session); try { session.get(Product.class,productID); //OR NATIVE QUREY session.createSQLQuery("SELECT id FROM `products` WHERE id = :productID") .setParameter("productID", productID).list(); } catch (Exception e) { // TODO: handle exception return false; }finally { HibernateUtil.closeSession(session); } } }

 

Related content