DAO Layer
The DAO class code PhoneDAOImpl implements the data access interface PhoneDAO which defines methods such as addPhone(), updatePhone(), listPhones(), getPhoneById() and removePhone() to access data from database.
Note that we are going to used @Repository Spring annotation.
The @Repository annotation is yet another stereotype that was introduced in Spring 2.0. This annotation is used to indicate that a class functions as a repository and needs to have exception translation applied transparently on it. The benefit of exception translation is that the service layer only has to deal with exceptions from Spring’s DataAccessException hierarchy, even when using plain JPA in the DAO classes.
PhoneDAO.java
package com.spring.demo.dao;
import java.util.List;
import com.spring.demo.model.Phone;
public interface PhoneDAO {
public void addPhone(Phone p);
public void updatePhone(Phone p);
public List<Phone> listPhones();
public Phone getPhoneById(int id);
public void removePhone(int id);
}
PhoneDAOImpl.java
package com.spring.demo.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import com.spring.demo.model.Phone;
@Repository
public class PhoneDAOImpl implements PhoneDAO {
private static final Logger logger = LoggerFactory.getLogger(PhoneDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
@Override
public void addPhone(Phone p) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(p);
logger.info("Phone saved successfully, Phone Details=" + p);
}
@Override
public void updatePhone(Phone p) {
Session session = this.sessionFactory.getCurrentSession();
session.update(p);
logger.info("Phone updated successfully, Phone Details=" + p);
}
@SuppressWarnings("unchecked")
@Override
public List<Phone> listPhones() {
Session session = this.sessionFactory.getCurrentSession();
List<Phone> phonesList = session.createQuery("from Phone").list();
for (Phone p : phonesList) {
logger.info("Phone List::" + p);
}
return phonesList;
}
@Override
public Phone getPhoneById(int id) {
Session session = this.sessionFactory.getCurrentSession();
Phone p = (Phone) session.load(Phone.class, new Integer(id));
logger.info("Phone loaded successfully, Phone details=" + p);
return p;
}
@Override
public void removePhone(int id) {
Session session = this.sessionFactory.getCurrentSession();
Phone p = (Phone) session.load(Phone.class, new Integer(id));
if (null != p) {
session.delete(p);
}
logger.info("Phone deleted successfully, phone details=" + p);
}
}