package tutorial.core.repositories.jpa;

import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import tutorial.core.models.entities.Message;
import tutorial.core.repositories.MessageRepo;

/**
 * 
 * @author Xavier
 */
@Repository
public class JpaMessageRepo implements MessageRepo {
    @PersistenceContext
    private EntityManager em;

    @Override
    public Message createMessage(Message data) {
        em.persist(data);
        return data;
    }

    @Override
    public List<Message> findAllMessages() {
        Query query = em.createQuery("SELECT b from Message b");
        return query.getResultList();
    }

    @Override
    public Message findMessage(Long id) {
        return em.find(Message.class, id);
    }

    /**
     *
     */
    @Override
    public void deleteAllMessages() {
        Query query = em.createQuery("DELETE from Message");
        int numDeletedMessages = query.executeUpdate();
    }
}
