在hibernate中更新和显示数据时遇到了一个奇怪的问题。有人能帮我吗!?
我在mysql中使用hibernate和spring。
我现在面临的问题是,任何更改都可以应用到数据库。但如果我在网页上加载更新的项目,它总是随机返回旧数据或新数据。
我确信这不是浏览器缓存的问题。我试图在dao类的getPost方法中打印出返回数据。有时候只是打印出错误的信息。
比方说,如果我多次更改文章内容,所有更改都可以存储在数据库中。但如果我不断刷新页面以显示更改的数据,它将随机显示以前的所有更改。
我尝试过用getPost方法加载数据的不同方法,但仍然面临相同的问题:
尝试了session.clear和session.flush
关闭二级缓存为:

<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.cache.use_structured_entries">false</prop>

加载数据的不同方式:session.load、session.get、hibernate query、Criteria,都有相同的问题。
在postDAO的getPost方法中:首先尝试用原生SQL加载数据,并与hibernate查询的结果进行比较。两个查询都返回旧数据。
代码:
public class Post implements Cloneable, Serializable {

    private String postID;
    private String content;
}

PostSelectController (controller):

public class PostSelectController extends AbstractController
{
....
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String id = request.getParameter("id");

        Course course = null;
        Vendor vendor = null;
        Post post = null;

        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName(getSuccessView());

        post = postService.getPost(id);

        modelAndView.addObject("post", post);

        return modelAndView;
    }
}

postService:

@Transactional(propagation=Propagation.SUPPORTS, isolation=Isolation.READ_COMMITTED, readOnly=true)
public class PostService
{
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
    public boolean updatePost(Post post) {

        System.out.println("service side::::::::::::::::::::::"+(post.getBestAnswer()!=null));
        if(post.getBestAnswer()!=null) System.out.println(">>>>>>>>"+post.getBestAnswer().getPostID());
        System.out.println("service side::::::::::::::::::::::"+(post.getBestAnswer()!=null));;

        return this.postDAO.updatePost(post);
    }

    public Post getPost(String postID) {
        return this.postDAO.getPost(postID);
    }
}

postDAO:

public class  PostDAO {
private SessionFactory sessionFactory;
...

public boolean updatePost(Post post) {
        boolean proceed = true;

        try {

            Session session = sessionFactory.getCurrentSession();
            session.merge(post); //tried session.update, same problem

            session.flush(); //it does not help

        } catch (Exception ex) {
            logger.error(post.getPostID() + " refused :: " + ex.getMessage());
            proceed = false;
        }
        return proceed;
    }


public Post getPost(String postID) {

        Session session = sessionFactory.getCurrentSession();
        try{
         PreparedStatement st = session.connection()
            .prepareStatement("select content from post where postid='"+postID+"'") ;

             ResultSet rs =st.executeQuery();
             while (rs.next()) {

                System.out.println("database::::::::::::::::::"+rs.getInt("content"));
                // tried to use native sql to load data from database and compare it with result of hibernate query.
                break;
             }
        }catch(Exception ex){

        }

        Criteria crit = session.createCriteria(Post.class);
        NaturalIdentifier natId = Restrictions.naturalId();
        natId.set("postID", postID);
        crit.add(natId);
        crit.setCacheable(false);

        List<Post> posts = crit.list();

        Post post = null;
        if(posts!=null)  post = posts.get(0);
        System.out.println("hibernate::::::::::::::::::"+post.getContent());


        return post;

    }

最佳答案

我也有同样的麻烦。我很快找到了答案。正如里卡多所说,问题在于没有干净地结束会话,因此会话被随机回收。我是在班上的教师那里做的。
例如(我在这里使用HybernateUtil):

 public yourHelper() {

        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
         if (session.isOpen()){
            session.close();
            session=HibernateUtil.getSessionFactory().openSession();
        }
    }

休眠设备代码:
    public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml)
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
            System.out.println("SRPU_INFO: Initial SessionFactory creation success.");
        } catch (Throwable ex) {
            // Log the exception.

            System.out.println("SRPU_INFO: Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

用于阅读的thanx

10-07 19:37
查看更多