×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: ture ture
Added: Apr 8, 2018 10:33 PM
Views: 7
Tags: no tags
  1. Creating DAO Layer
  2. Create a UserDao Interface under springmvc_example.dao package and write the following code in it
  3.  
  4. package springmvc_example.dao;
  5.  
  6. import java.util.List;
  7.  
  8. import springmvc_example.model.User;
  9.  
  10. public interface UserDao {
  11.  
  12.  public List getListUser();
  13.  
  14.  public void saveOrUpdate(User user);
  15.  
  16.  public void deleteUser(int id);
  17.  
  18.  public User findUserById(int id);
  19.  
  20. }
  21.  
  22. Create a UserDaoImpl class implements UserDao Interface under springmvc_example.dao package and write the following code in it
  23.  
  24. package springmvc_example.dao;
  25.  
  26. import java.util.List;
  27.  
  28. import org.hibernate.Criteria;
  29. import org.hibernate.Session;
  30. import org.hibernate.SessionFactory;
  31. import org.springframework.beans.factory.annotation.Autowired;
  32. import org.springframework.stereotype.Repository;
  33.  
  34. import springmvc_example.model.User;
  35.  
  36. public class UserDaoImpl implements UserDao {
  37.  
  38.  @Autowired
  39.  private SessionFactory sessionFactory;
  40.  
  41.  protected Session getSession(){
  42.   return sessionFactory.getCurrentSession();
  43.  }
  44.  
  45.  @SuppressWarnings("unchecked")
  46.  public List getListUser() {
  47.   Criteria criteria = getSession().createCriteria(User.class);
  48.  
  49.   return (List) criteria.list();
  50.  }
  51.  
  52.  public void saveOrUpdate(User user) {
  53.   getSession().saveOrUpdate(user);
  54.  }
  55.  
  56.  public void deleteUser(int id) {
  57.   User user = (User) getSession().get(User.class, id);
  58.   getSession().delete(user);
  59.  }
  60.  
  61.  public User findUserById(int id) {
  62.   return (User) getSession().get(User.class, id);
  63.  }
  64.  
  65. }
  66.