package dao.hibernate;

import java.util.List;

import model.Product;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import dao.ProductDao;

public class ProductDaoImpl implements ProductDao {
    private Session session;
    
    public ProductDaoImpl(Session session) {
        this.session = session;
    }
    public void save(Product product) throws Exception {
        this.session.saveOrUpdate(product);
    }
    
    public Product findById(Long id) throws Exception {
        return (Product)this.session.load(Product.class, id);
    }
    
    public void delete(Product product) throws Exception {
        this.session.delete(product);
    }

    public List<Product> findAll() throws Exception {
        Criteria criteria = this.session.createCriteria(Product.class);
        return criteria.list();
    }
    
    public List<Product> findByCategoryName(String name) throws Exception {
        Criteria criteria = this.session.createCriteria(Product.class)
                                        .createAlias("category", "c")
                                        .add(Restrictions.like("c.name", "%"+name+"%"));
        return criteria.list();
    }
    public List<Product> findByName(String name) throws Exception {
        Criteria criteria = this.session.createCriteria(Product.class)
                                        .add(Restrictions.like("name", "%"+name+"%"));
        return criteria.list();
    }
}
