开发者

2 ways to get the latest row from db

开发者 https://www.devze.com 2023-04-06 10:24 出处:网络
I have a struts2 app with spring transactions and JPA2 over hibernate. The problem is that I have some rows in the database that are changed by an external source (some mysql triggers) and in my front

I have a struts2 app with spring transactions and JPA2 over hibernate. The problem is that I have some rows in the database that are changed by an external source (some mysql triggers) and in my front app I have an ajax script that checks this values every 2 seconds. I always need to get the latest value, and not a cached one, and for this I found 2 solutions :

String sql = "FROM MyEntity WHERE xId=:id AND connect!=0 AND complete=0 AND (error=NULL OR error=0)";
  Query q = this.em.createQuery(sql).setHint("org.hibernate.cacheable", false).setParameter("agId", agentId);      
        rs = q.getResultList();
        if(rs.size() == 1){
            intermedObj = (Intermed) rs.get(0);
        }

and the other:

 String sql = "FROM MyEntity WHERE xxId=:id AND connect!=0 AND complete=0 AND (error=NULL OR error=0)";
        Query q = this.em.createQuery(sql).setParameter("agId", agentId);
        rs = q.getResultList();
        if(rs.size() == 1){
            int开发者_运维技巧ermedObj = (Intermed) rs.get(0);
            //get latest object from DB
            em.refresh(intermedObj);
        }

em is a instance of EntityManager which is managed by spring.

So, the question is: which is the best approach from these 2? Or maybe there is a better one ?


So you are right, I used hql there, I still have to learn a lot about hibernate an jpa, and java in general. So I guess that the correct way to write that cod in JPQL would be:

 String sql = "SELECT m FROM MyEntity m WHERE m.xxId=:id AND m.connect!=0 AND m.complete=0 AND (m.error!=1)";
        Query q = this.em.createQuery(sql).setParameter("agId", agentId);
        rs = q.getResultList();
        if(rs.size() == 1){
            intermedObj = (Intermed) rs.get(0);
            //get latest object from DB
            em.refresh(intermedObj);
        }

So the question would be, is this the proper way to make sure that I got the latest row from DB and not a cached record?

As regarding leve2 cache question I do not know if this is activated. How do I check that?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号