Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package net.example.com.dao;
- import java.util.List;
- public interface GenericDao<T> {
- public T findById(int id);
- public List<T> findAll();
- public void update(T entity);
- public void save(T entity);
- public void delete(T entity);
- }
- /* ------------------------------------------------------ */
- package net.example.com.dao;
- import java.io.Serializable;
- import java.util.List;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Scope;
- @Scope("prototype")
- public abstract class GenericHibernateDaoImpl<T extends Serializable> implements GenericDao<T> {
- private Class<T> clazz;
- @Autowired
- private SessionFactory sessionFactory;
- public final void setClazz(Class<T> clazzToSet) {
- this.clazz = clazzToSet;
- }
- @SuppressWarnings("unchecked")
- public T findById(int id) {
- return (T) getCurrentSession().get(clazz, id);
- }
- @SuppressWarnings("unchecked")
- public List<T> findAll() {
- return getCurrentSession().createQuery("FROM " + clazz.getName()).list();
- }
- public void update(T entity) {
- getCurrentSession().update(entity);
- }
- public void save(T entity) {
- getCurrentSession().save(entity);
- }
- public void delete(T entity) {
- getCurrentSession().delete(entity);
- }
- protected final Session getCurrentSession(){
- return sessionFactory.getCurrentSession();
- }
- }
- /* ------------------------------------------------------ */
- package net.example.com.dao;
- import java.util.List;
- import net.example.com.entity.User;
- public interface UserDao extends GenericDao<User> {
- public User findByEmail(String email);
- public List<User> findEnabled();
- }
- /* ------------------------------------------------------ */
- package net.example.com.dao;
- import java.util.List;
- import org.hibernate.SessionFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Repository;
- import net.example.com.entity.User;
- @Repository
- public class UserDaoImpl extends GenericHibernateDaoImpl<User> implements UserDao {
- public User findByEmail(String email) {
- return (User) getCurrentSession()
- .createQuery("FROM User WHERE email = :email")
- .setString("email", email).uniqueResult();
- }
- @SuppressWarnings("unchecked")
- public List<User> findEnabled() {
- return getCurrentSession()
- .createQuery("FROM User WHERE enabled = true")
- .list();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment