package com.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;


import com.entities.Product;

public class ProductDao {
	private SessionFactory factory;

	public ProductDao(SessionFactory factory) {
		super();
		this.factory = factory;
	}
	
	public int saveProduct(Product product) {
		
		
		Session session = this.factory.openSession();
		Transaction tx = session.beginTransaction();
		
		int pId= (int)session.save(product);
		
		tx.commit();
		
		session.close();
		
	
	return pId;
}
	
public List<Product> getAllProducts(){
		
		
		Session s = this.factory.openSession();
		
		Query<?> query = s.createQuery("from Product");
		@SuppressWarnings("unchecked")
		List<Product> list = (List<Product>) query.list();
		
		return list;
	}

public List<Product> getAllProductsById(int cid){
	
	
	Session s = this.factory.openSession();
	
	Query<?> query = s.createQuery("from Product as p where p.category.categoryId =: id");
	query.setParameter("id", cid);
	@SuppressWarnings("unchecked")
	List<Product> list = (List<Product>) query.list();
	
	return list;
}


}
