crud operations specialized for suppliers
package com.project.dao;
import java.util.List;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import com.project.dto.SupplierFilter;
import com.project.model.Item;
import com.project.model.Supplier;
@Repository
public class SupplierDao extends GenericDao<Supplier> {
public List<Supplier> findByName(String term) {
TypedQuery<Supplier> query = entityManager.createQuery("SELECT s FROM Supplier s WHERE s.name = :term",
Supplier.class);
query.setParameter("term", term);
return query.getResultList();
}
public List<Supplier> findByPhone(String term) {
TypedQuery<Supplier> query = entityManager.createQuery("SELECT s FROM Supplier s WHERE s.phone = :term",
Supplier.class);
query.setParameter("term", term);
return query.getResultList();
}
public List<Item> getItems(Long id) {
TypedQuery<Item> query = entityManager.createQuery("SELECT i FROM Item i WHERE i.supplier.id = :id",
Item.class);
query.setParameter("id", id);
return query.getResultList();
}
public Long supplierCount(SupplierFilter filter) {
String name = !filter.getName().isEmpty() ? "s.name LIKE :name " : "";
String phone = !filter.getPhone().isEmpty() ? "s.phone LIKE :phone " : "";
String operator = name.isEmpty() || phone.isEmpty() ? "" : "and ";
String sql = String.format("SELECT COUNT(*) FROM Supplier s %s%s%s%s",
!name.isEmpty() || !phone.isEmpty() ? "WHERE " : "", name, operator, phone);
TypedQuery<Long> query = entityManager.createQuery(sql, Long.class);
if (!phone.isEmpty())
query.setParameter("phone", "%" + filter.getPhone() + "%");
if (!name.isEmpty())
query.setParameter("name", "%" + filter.getName() + "%");
return (Long) query.getSingleResult();
}
public List<Supplier> filterSuppliers(SupplierFilter filter) {
String name = !filter.getName().isEmpty() ? "s.name LIKE :name " : "";
String phone = !filter.getPhone().isEmpty() ? "s.phone LIKE :phone " : "";
String operator = name.isEmpty() || phone.isEmpty() ? "" : "and ";
String sql = String.format("SELECT s FROM Supplier s %s%s%s%s",
!name.isEmpty() || !phone.isEmpty() ? "WHERE " : "", name, operator, phone);
TypedQuery<Supplier> query = entityManager.createQuery(sql, Supplier.class);
query.setFirstResult(filter.getOffset());
query.setMaxResults(filter.getLimit());
if (!phone.isEmpty())
query.setParameter("phone", "%" + filter.getPhone() + "%");
if (!name.isEmpty())
query.setParameter("name", "%" + filter.getName() + "%");
return query.getResultList();
}
}