/**
*
*/
package com.blogspot.piergiuseppe82.struts2intro.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.blogspot.piergiuseppe82.struts2intro.dto.Persona;
import com.blogspot.piergiuseppe82.struts2intro.dto.Recapito;
/**
* @author placava
*
*/
@Component("personaDao")
@Transactional
public class PersonaDaoImpl implements PersonaDao {
private EntityManager em;
@PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
/* (non-Javadoc)
* @see com.blogspot.piergiuseppe82.struts2intro.dao.PersonaDao#allPersona()
*/
@SuppressWarnings("unchecked")
public List<Persona> allPersona() {
Query query = em.createQuery("select p FROM Persona p");
return query.getResultList();
}
/* (non-Javadoc)
* @see com.blogspot.piergiuseppe82.struts2intro.dao.PersonaDao#delete(com.blogspot.piergiuseppe82.struts2intro.dto.Persona)
*/
public void remove(int id) {
Persona persona = find(id);
if (persona != null) {
persona.setRecapiti(find(persona.getId()).getRecapiti());
em.remove(persona);
}
}
/* (non-Javadoc)
* @see com.blogspot.piergiuseppe82.struts2intro.dao.PersonaDao#insert(com.blogspot.piergiuseppe82.struts2intro.dto.Persona)
*/
public void save(Persona persona) {
if(persona.getId() == null){
em.persist(persona);
}else{
persona.setRecapiti(find(persona.getId()).getRecapiti());
em.merge(persona);
}
}
/* (non-Javadoc)
* @see com.blogspot.piergiuseppe82.struts2intro.dao.PersonaDao#find(int)
*/
public Persona find(int id) {
return em.find(Persona.class, id);
}
/* (non-Javadoc)
* @see com.blogspot.piergiuseppe82.struts2intro.dao.PersonaDao#addRecapito(int, com.blogspot.piergiuseppe82.struts2intro.dto.Recapito)
*/
public void addRecapito(int idPersona, Recapito recapito) {
if(recapito.getId() != null){
Persona persona = find(idPersona);
recapito.setPersona(persona);
em.merge(recapito);
return;
}
Persona persona = find(idPersona);
if(persona != null){
persona.getRecapiti().add(recapito);
em.merge(persona);
}
}
/* (non-Javadoc)
* @see com.blogspot.piergiuseppe82.struts2intro.dao.PersonaDao#getRecapito(int)
*/
public Recapito getRecapito(int id) {
return em.find(Recapito.class, id);
}
/* (non-Javadoc)
* @see com.blogspot.piergiuseppe82.struts2intro.dao.PersonaDao#removeRecapito(int)
*/
public void removeRecapito(int id) {
Recapito recapito = getRecapito(id);
if(recapito != null)
em.remove(recapito);
}
}