bc8.movies.dao.ActorDaoImpl.java Source code

Java tutorial

Introduction

Here is the source code for bc8.movies.dao.ActorDaoImpl.java

Source

/*`
 * 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 bc8.movies.dao;

import bc8.movies.entities.Actor;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Catalin
 */
@Repository
public class ActorDaoImpl {

    @PersistenceContext
    EntityManager em;

    public void addActor(Actor actor) {
        em.persist(actor);
    }

    public void addActors(Set<Actor> toAdd) {
        Iterator<Actor> it = toAdd.iterator();

        while (it.hasNext()) {
            Actor currActor = it.next();
            em.persist(currActor);
        }
    }

    public Actor getActor(String actorName) {
        Query query = em.createQuery("select actor from Actor actor where actor.name= :actorName");
        query.setParameter("actorName", actorName);
        return (Actor) query.getSingleResult();
    }

    public List<Actor> getAllActors() {
        Query query = em.createQuery("select actor from Actor actor");
        return query.getResultList();
    }

    public List<Actor> getActorsForMovie(String movieName) {
        Query query = em.createNativeQuery(
                "Select a.name FROM " + "actors AS a, " + "actors_movies AS am, " + "movies AS m " + "WHERE "
                        + "m.id = am.movieId AND " + "am.actorId = a.id AND " + "m.name = :movieName");

        query.setParameter("movieName", movieName);

        return query.getResultList();
    }
}