Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mycompany.springrest.dao; import com.mycompany.springrest.model.User; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * * @author ?? */ @Repository @Transactional public class UserDAOImpl implements UserDAO { private static final Logger logger = LoggerFactory.getLogger(UserDAOImpl.class); @Autowired private SessionFactory sessionFactory; public void serSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public void addUser(User user) { Session session = this.sessionFactory.getCurrentSession(); session.persist(user); logger.info("User saved successfully, User Details=" + user); } @Override public void updateUser(User user) { Session session = this.sessionFactory.getCurrentSession(); session.update(user); logger.info("User updated successfully, User Details=" + user); } @SuppressWarnings("unchecked") @Override public List<User> listUsers() { Session session = this.sessionFactory.getCurrentSession(); List<User> usersList = session.createQuery("from User").list(); for (User user : usersList) { logger.info("User List::" + user); } return usersList; } @Override @SuppressWarnings("unchecked") public User getUserById(int id) { Session session = this.sessionFactory.getCurrentSession(); User user = (User) session.load(User.class, new Integer(id)); logger.info("User loaded successfully, User details=" + user); return user; } @Override @SuppressWarnings("unchecked") public void removeUser(int id) { Session session = this.sessionFactory.getCurrentSession(); User user = (User) session.load(User.class, new Integer(id)); if (null != user) session.delete(user); logger.info("User deleted successfully, User details=" + user); } @Override public User getUserByName(String username) { Session session = this.sessionFactory.getCurrentSession(); Criteria crit = session.createCriteria(User.class); crit.add(Restrictions.eq("userName", username)); return (User) crit.uniqueResult(); } }