Esempio n. 1
0
  @Override
  public void saveOrUpdate(Movie movie) {
    Connection conn = null;
    try {
      conn = ds.getConnection();

      PreparedStatement pst;
      if (movie.getId() == null) { // insert
        long id = 0;
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery("select max(MOVIE_ID) from MOVIES");
        if (rs.next()) {
          id = rs.getLong(1) + 1;
        }
        movie.setId(id);

        pst =
            conn.prepareStatement(
                "INSERT INTO MOVIES (MOVIE_ID, MOVIE_TITLE, MOVIE_RELEASEDATE, MOVIE_RENTED, PRICECATEGORY_FK) VALUES (?,?,?,?,?)");
        pst.setLong(1, id);
        pst.setString(2, movie.getTitle());
        pst.setDate(3, new Date(movie.getReleaseDate().getTime()));
        pst.setBoolean(4, movie.isRented());
        pst.setLong(5, movie.getPriceCategory().getId());
        pst.execute();
      } else { // update
        pst =
            conn.prepareStatement(
                "UPDATE MOVIES SET MOVIE_TITLE=?, MOVIE_RELEASEDATE=?, MOVIE_RENTED=?, PRICECATEGORY_FK=? where MOVIE_ID=?");
        pst.setLong(5, movie.getId());
        pst.setString(1, movie.getTitle());
        pst.setDate(2, new Date(movie.getReleaseDate().getTime()));
        pst.setBoolean(3, movie.isRented());
        pst.setLong(4, movie.getPriceCategory().getId());
        pst.execute();
      }
    } catch (SQLException e) {
      throw new RuntimeException(e);
    } finally {
      if (conn != null) {
        try {
          conn.close();
        } catch (SQLException e) {
          throw new RuntimeException(e);
        }
      }
    }
  }
  @SuppressWarnings("unchecked")
  public void deleteMovie(Movie movie) throws RentalServiceException {
    if (movie == null) {
      throw new RentalServiceException("'movie' parameter is not set!");
    }
    if (movie.isRented()) {
      throw new RentalServiceException("movie is still used");
    }

    if (movieDAO instanceof ManagedDAO<?>) {
      movie = ((ManagedDAO<Movie>) movieDAO).manage(movie);
    }

    movieDAO.delete(movie);

    if (log.isDebugEnabled()) {
      log.debug("movie[" + movie.getId() + "] deleted");
    }
  }