70 lines
2.0 KiB
Java
Raw Normal View History

2019-11-15 16:52:21 +01:00
package at.technikumwien.movies;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.logging.Logger;
@Stateless
public class MoviesService {
private static final Logger LOGGER = Logger.getLogger(MoviesService.class.getName());
@Resource
private SessionContext context;
@PersistenceContext(unitName = "MoviesPU")
private EntityManager em;
public Movies findById(long id) {
LOGGER.info("findById() >> id=" + id);
Movies movies = em.find(Movies.class, id);
if (movies == null) {
throw new EntityNotFoundException("can't find movie with id=" + id);
}
return movies;
}
public List<Movies> findByTitle(String title) {
LOGGER.info("findByTitle() >> title=" + title);
return em.createNamedQuery("Movies.selectByTitle", Movies.class)
.setParameter("title", "%" + title + "%")
.getResultList();
}
public List<Movies> findAll() {
LOGGER.info("findAll()");
return em.createNamedQuery("Movies.selectAll", Movies.class) //JPQL -> java persistence query language
.getResultList();
}
public void removeById(long id) {
LOGGER.info("removeById() >> id=" + id);
Movies movies = findById(id);
em.remove(movies); //managed news required
}
public void save(Movies movies) {
// TODO: Search for actors, studio based on fields we get
// If exists -> Replace by found ID
// Else -> Error!
LOGGER.info("save() >> movies" + movies);
if (movies.getId() == null) {
em.persist(movies);
} else {
findById(movies.getId()); //checks if movies exists
em.merge(movies);
}
// TODO: On error: context.setRollbackOnly();
// or: throw new EJBException("Can't save ...")
}
}