Home > AI > Backend > SpringBoot > mysql-connector-java >

Entity – Movie

@Data
@Entity
@Table(name = "MOVIE")
public class Movie {

    @Id
    private Long id;

    private String movieName;

    private Integer releaseYear;

    private String language;

    // standard constructor, getters, setters
}

MovieService.java

@Service
public class MovieService {

    @PersistenceContext // or even @Autowired
    private EntityManager em;

    public void saveMovie() {

        em.getTransaction().begin();

        Movie movie = new Movie();
        movie.setId(1L);
        movie.setMovieName("The Godfather");
        movie.setReleaseYear(1972);
        movie.setLanguage("English");

        em.persist(movie);
        em.getTransaction().commit();
    }


    public Movie getMovie(Long movieId) {
        Movie movie = em.find(Movie.class, new Long(movieId));
        em.detach(movie);
        return movie;
    }


    public void mergeMovie() {
        Movie movie = getMovie(1L);
        em.detach(movie);
        movie.setLanguage("Italian");
        em.getTransaction().begin();
        em.merge(movie);
        em.getTransaction().commit();
    }



    public List<?> queryForMovies() {
        List<?> movies = em.createQuery("SELECT movie from Movie movie where movie.language = ?1")
                .setParameter(1, "English")
                .getResultList();
        return movies;
    }


    public void removeMovie() {
        em.getTransaction().begin();
        Movie movie = em.find(Movie.class, new Long(1L));
        em.remove(movie);
        em.getTransaction().commit();
    }
}

Leave a Reply