/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dao.impl;

import dao.DaoPoslovniPartner;
import domen.AbstractPoslovniPartner;
import domen.PravnoLice;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author student
 */
public class DaoPoslovniPartnerImpl implements DaoPoslovniPartner {
    EntityManagerFactory emf;

    public DaoPoslovniPartnerImpl() {
        emf = Persistence.createEntityManagerFactory("JPA1PU");
    }
    
    
    @Override
    public void sacuvaj(AbstractPoslovniPartner pp) {
        
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(pp);
        em.getTransaction().commit();
        em.close();
    }

    @Override
    public PravnoLice pronadjiPravnoLice(PravnoLice pl) throws Exception {
        EntityManager em = emf.createEntityManager();
        
        List<PravnoLice> lista = em.createQuery("SELECT pp FROM PravnoLice pp WHERE pp.maticniBroj =:maticnibroj")
                .setParameter("maticnibroj", pl.getMaticniBroj()).getResultList();
        
        em.close();
        PravnoLice pLice = null;
        if (lista.size() > 1) throw new Exception("Ima vise pravnih lica.");
        if (!lista.isEmpty()) pLice = lista.get(0);
        return pLice;
    }
    
}
