Hibernate并没有给我最近保存的记录

时间:2016-02-26 03:40:11

标签: hibernate

我正在使用Struts + Hibernate,我创建了一个应用程序,我可以保存电影记录并显示它们或搜索电影。但我面临一个奇怪的问题。当我保存新的电影记录时,它会保存记录。之后我选择电影列表来显示电影表中的所有记录。它没有在第一次尝试中显示新更新的记录。当我第二次点击显示电影列表时,它肯定会显示新行。为什么hibernate不会一次性给我最近插入的行。

这是我的控制器添加电影。

public class AddMovieAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        SessionFactory factory = (SessionFactory) getServlet().getServletContext().getAttribute("factory");
        AddMovieForm formFilled = (AddMovieForm) form;
        MoviesDaoImpl moviesDaoImpl = new MoviesDaoImpl(factory);

        ActionMessages actionMessages = new ActionMessages();
        if (moviesDaoImpl.addMovie(formFilled.getMovieName(), formFilled.getMovieReleaseYear(),
                formFilled.getMovieLeadActor(), formFilled.getMovieHouseName())) {
            actionMessages.add("success", new ActionMessage("message.success"));
        }
        saveMessages(request, actionMessages);
        return mapping.findForward("samepage");
    }
}

这是我的显示控制器

public class DisplayMoviesAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        SessionFactory factory = (SessionFactory) getServlet().getServletContext().getAttribute("factory");
        MoviesDaoImpl moviesDaoImpl = new MoviesDaoImpl(factory);
        List<Movie> movies = moviesDaoImpl.getAllMovies();
        request.setAttribute("movies", movies);
        return mapping.findForward("list");
    }
}

这是我的MoviesDaoImpl.java

public class MoviesDaoImpl implements MoviesDao {

    private SessionFactory factory;

    public MoviesDaoImpl(SessionFactory factory) {
        this.factory = factory;
    }

    @Override
    public List<Movie> getMovieByName(String name) {
        Session session = factory.openSession();
        session.beginTransaction();
        try {
            String hql = "FROM Movie M WHERE M.movieName like :movieName";
            org.hibernate.Query query = session.createQuery(hql);
            query.setParameter("movieName", "%" + name + "%");
            @SuppressWarnings("unchecked")
            List<Movie> movies = query.list();
            session.getTransaction().commit();
            return movies;
        } catch (HibernateException e) {
            e.printStackTrace();
            return null;
        } finally {
            session.close();
        }
    }

    @Override
    public List<Movie> getAllMovies() {
        Session session = factory.openSession();
        session.beginTransaction();
        @SuppressWarnings("unchecked")
        List<Movie> movies = (List<Movie>) session.createQuery("From Movie").list();
        session.getTransaction().commit();
        session.close();
        return movies;
    }

    @Override
    public boolean addMovie(String movieName, String movieReleaseYear, String movieLeadActor, String movieHouse) {
        Session session = factory.openSession();
        try {
            session.beginTransaction();
            // Check if movie is already exists or not. Why create duplicate rows of same movie
            Movie movie = getExistingMovieByName(movieName);
            if(movie==null){
                movie = new Movie();
            }
            movie.setMovieName(movieName);
            movie.setMovieReleaseYear(movieReleaseYear);
            // Check if actor already exists or not. Why create duplicate rows of same actor
            Actor actor = getExistingActor(movieLeadActor);
            if(actor!=null){
                movie.setLeadActor(actor);
            }else{
                actor = new Actor();
                actor.setActorName(movieLeadActor);
                movie.setLeadActor(actor);
            }
            // Check if Movie House already exists or not. Why create duplicate rows of same Movie House
            MoviesHouse moviesHouse = getMovieHouseId(movieHouse);
            if (moviesHouse != null) {
                System.out.println("MovieHouse Exists no need to create new record");
                movie.setMovieHouse(moviesHouse);
            } else {
                moviesHouse = new MoviesHouse();
                moviesHouse.setMovieHouseName(movieHouse);
                movie.setMovieHouse(moviesHouse);
                System.out.println("create movie house");
            }
            session.saveOrUpdate(movie);
            session.saveOrUpdate(actor);
            session.saveOrUpdate(moviesHouse);
            session.getTransaction().commit();

        } catch (HibernateException e) {
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
        /*Session session1 = factory.openSession();
        session1.beginTransaction();
        @SuppressWarnings("unchecked")
        List<Movie> movies = session1.createQuery("From Movie").list(); 
        for(Movie m:movies){
            System.out.println(m);
        }
        session1.getTransaction().commit();
        session1.close();*/
        return true;
    }

    public MoviesHouse getMovieHouseId(String movieHouseName) {
        Session session = factory.openSession();
        session.beginTransaction();
        Criteria crit = session.createCriteria(MoviesHouse.class);
        crit.add(Restrictions.eq("movieHouseName", movieHouseName));
        @SuppressWarnings("unchecked")
        List<MoviesHouse> results = crit.list();
        MoviesHouse moviesHouse = null;
        try {
            moviesHouse = (MoviesHouse) results.get(0);
            session.getTransaction().commit();
            return moviesHouse;
        } catch (Exception e) {
            return moviesHouse;
        } finally {
            session.close();
        }
    }
    public Actor getExistingActor(String actorName){
        Session session = factory.openSession();
        session.beginTransaction();
        Criteria crit = session.createCriteria(Actor.class);
        crit.add(Restrictions.eq("actorName", actorName));
        @SuppressWarnings("unchecked")
        List<Actor> results = crit.list();
        Actor actor = null;
        try {
            actor = (Actor) results.get(0);
            session.getTransaction().commit();
            return actor;
        } catch (Exception e) {
            return actor;
        } finally {
            session.close();
        }
    }

    public Movie getExistingMovieByName(String movieName){
        Session session = factory.openSession();
        session.beginTransaction();
        Criteria crit = session.createCriteria(Movie.class);
        crit.add(Restrictions.eq("movieName", movieName));
        @SuppressWarnings("unchecked")
        List<Movie> results = crit.list();
        Movie movie = null;
        try {
            movie = (Movie) results.get(0);
            session.getTransaction().commit();
            return movie;
        } catch (Exception e) {
            return movie;
        } finally {
            session.close();
        }
    }
}

我在添加新电影后第一次调用DisplayMoviesAction。新创建的记录未获取。但是当我再次点击列表电影时,它再次调用DisplayMovieAction,这次我在列表中看到了新记录。任何人都可以帮我解决这里发生的事情吗?

1 个答案:

答案 0 :(得分:-1)

session.flush();

之前使用session.getTransaction().commit();