Java Reference
In-Depth Information
LISTING 12‐2: The DAO interface
package com.devchronicles.dataaccessobject;
import java.util.List;
public interface MovieDAO {
public void addMovie(Movie movie);
public Movie getMovie(int id);
public void deleteMovie(int id);
public void updateMovie(Movie movie);
public List<Movie> getAllMovies();
}
Now for the concrete implementation of the DAO interface shown in Listing 12‐3. Here you imple-
ment the CRUD operations. Notice that the constructor accepts an instance of the EntityManager .
r
This instance is associated with a persistence context that is dei ned in persistence.xml . The
EntityManager API provides create, remove, and persistence functionality as well as the ability to
create queries. Any transient i eld would not be saved or retrieved from the database so expect the
data on the transient i eld to be reset each time the object is re-created.
LISTING 12‐3: The implementation of the DAO interface
package com.devchronicles.dataaccessobject;
import java.util.List;
import javax.persistence.EntityManager;
public class MovieDAOImpl implements MovieDAO{
private EntityManager em;
public MovieDAOImpl(EntityManager em) {
this.em = em;
}
@Override
public void addMovie(Movie movie) {
em.persist(movie);
}
@Override
public Movie getMovie(int id) {
return getAllMovies().get(id);
}
@Override
public void deleteMovie(int id) {
em.remove(getMovie(id));
continues
Search WWH ::




Custom Search