package dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.*;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import model.Unit;
@Repository
public class Dao {
@PersistenceContext
private EntityManager em;
public List<Unit> findAllDepartments() {
TypedQuery<Unit> query = em.createQuery("SELECT p FROM Unit p",
Unit.class);
return query.getResultList();
}
@Transactional
public void deleteAllData() {
List<Unit> units = findAllDepartments();
if (!units.isEmpty()) {
Query query = em.createNativeQuery("TRUNCATE SCHEMA public AND COMMIT");
query.executeUpdate();
} else {
findAllDepartments();
}
}
@Transactional
public void deleteDataById(Long id) {
Unit unit = em.find(Unit.class, id);
if (unit != null) {
em.remove(unit);
}
}
@Transactional
public void deleteDataByCode(String code) {
Query query = em.createQuery("delete from Unit u where u.code = :code");
query.setParameter("code", code);
query.executeUpdate();
}
public List<Unit> fullTextSearch(String userInput) {
TypedQuery<Unit> query = em.createQuery(
"SELECT p FROM Unit p WHERE UPPER(name) LIKE :userInput",
Unit.class);
query.setParameter("userInput", "%" + userInput.toUpperCase() + "%");
return query.getResultList();
}
public Unit getUnitByCode(String super_unit_id) {
TypedQuery<Unit> query = em.createQuery(
"SELECT p FROM Unit p WHERE p.code =:code", Unit.class);
query.setParameter("code", super_unit_id);
return query.getSingleResult();
}
public Unit getUnitById(long id) {
return em.find(Unit.class, id);
}
public List<Unit> getSubUnitById(Long id) {
TypedQuery<Unit> query = em.createQuery(
"SELECT p FROM Unit p WHERE p.super_unit_id =:id", Unit.class);
query.setParameter("id", id);
return query.getResultList();
}
public Map<String, String> getChannelTypes() {
Map<String, String> map = new HashMap<String, String>();
map.put("channelType.tel", "Telefon");
map.put("channelType.mail", "Mail");
return map;
}
@Transactional
public void save(Unit unit) {
em.persist(unit);
}
}