java - Web 服务响应未随数据库交互更新

标签 java mysql hibernate web-services rest

简介

I have a JavaEE Application which consists in a RESTFul Web Service. This WS is responsible to receive some requests and answer with XMLs. There are services to store and services to capture information of a MySQL DB.
The system was done using APIs like JAX-WS and JAX-B and the framework Hibernate for data persistence.

问题

When I update, delete or insert anything in my DB, directly or through a service of the WS, and try to see the result through a service, the differences doesn't appears unless I restart my WS.

可能性

I believe it's about Hibernate caching but I didn't find anything that help me to fix it.

有人遇到过这个问题吗?有什么想法吗?

hibernate .cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/context_server</property>
    <property name="hibernate.connection.username">user</property>
    <property name="hibernate.connection.password"></property>

    <mapping class="br.marcelo.bean.CsMediaAudio"/>
    <mapping class="br.marcelo.bean.CsMediaImage"/>
    <mapping class="br.marcelo.bean.CsMediaVideo"/>
    <mapping class="br.marcelo.bean.CsContext"/>
    <mapping class="br.marcelo.bean.CsMedia"/>
    <mapping class="br.marcelo.bean.CsResource"/>
    <mapping class="br.marcelo.bean.CsUser"/>
  </session-factory>
</hibernate-configuration>

获取信息的服务:

@GET
@Path("/getResourceByIdXML/{id}")
@Produces(MediaType.APPLICATION_XML)
public CsResource getResourceByIdXML(@PathParam("id")Long id) {     
    return new DAOResource().find(id);
}

类:DAOResource,上面使用了find方法:

public class DAOResource extends DAOGenerics<CsResource, Long> {
    private final Session s;

    public DAOResource()
    {
        s = HibernateSessionFactory.getSession();
    }

    @Override
    public CsResource find(Long id) {
       try {
            s.flush();
            s.clear();
            String sql = "from CsResource where id = :id";
            Query qr = s.createQuery(sql);
            qr.setParameter("id", id);

            return (CsResource) qr.uniqueResult();

        }catch(HibernateException e){
            System.out.println(e);
            return null;
        } finally {
            s.close();
        }
    }
}

带有 getSession 方法的 HibernateSessionFactory 类:

public class HibernateSessionFactory {

    private static SessionFactory sf;
    static
    {
        try
        {
            sf = new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
        }
        catch (Exception erro)
        {
            System.err.println(erro);
            sf = null;
        }
    }

    public static Session getSession()
    {
        return sf.openSession();
    }


    public static Connection getConnection(){

        try {
            SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) sf;
            ConnectionProvider connectionProvider = (ConnectionProvider)sessionFactoryImplementation.getConnectionProvider();

            java.sql.Connection connection = connectionProvider.getConnection();            

            return connection;
        } catch (SQLException ex) {
            Logger.getLogger(HibernateSessionFactory.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

}

编辑:

调用 flush() 和 clear() 方法的 DAOGenerics 类

public abstract class DAOGenerics<K, G> {

    private final Session s;

    public DAOGenerics()
    {
        s = HibernateSessionFactory.getSession();
    } 

    public abstract K buscar(G obj);

    public abstract List<K> buscarTodos();

    public boolean inserir(K obj){
        try {
            s.flush();
            s.clear();
            s.getTransaction().begin();
            s.saveOrUpdate(obj);                
            s.getTransaction().commit();
            s.close();
            return true;
        }
        catch (HibernateException erro){

            System.out.println(erro.getMessage());
            s.flush();
            s.clear();
            s.getTransaction().rollback();
            s.close();
            return false;
        }

    }

    public void apagar(K obj) {
        try {
            apagar(obj, s);
        } finally {
            s.flush();
            s.clear();
            s.close();
        }
    }

    public void apagar(K obj, Session s) {

        try {
            s.flush();
            s.clear();
            s.getTransaction().begin();
            s.delete(obj);                
            s.getTransaction().commit();
        }
        catch (HibernateException erro){
            System.out.println(erro);
            s.flush();
            s.clear();
            s.getTransaction().rollback();
        }finally{
            s.close();
        }
    }


}

最佳答案

是的,如果你在 hibernate 的“ View ”之外更改某些内容,hibernate 缓存不会意识到这一点。所以 2 个选项:

关于java - Web 服务响应未随数据库交互更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32639910/

相关文章:

java - Selenium 与身份验证弹出窗口交互

mysql - 使用 MySQL,使用第二列作为条件返回具有重复 ID 的表中的特定用户 ID

mysql - SQL - 如何执行这种类似连接的操作?

java - 使用 Hibernate (JSR 303) 方法验证来比较参数

java - JPA 2.1、Hibernate 4.3、Spring 4.0 数据未保存到数据库

java - Thymeleaf 未加载 css 和 js

java - 字符串比较库

MySQL 配置。需要很多连接

java - dao、tx、服务结构 : where to place a method querying an abstract entity?

java - 使用gradle maven插件时如何设置java目标和源版本?