0

im new to all this hibernate+spring stuff, learning it in a real project ( yeah i like doing it)...

in my applicationcontext.xml i got sessionfactory and transactionManager (both using default name) set.

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="/WEB-INF/database.properties" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.url}" p:username="${jdbc.username}"
    p:password="${jdbc.password}" />


<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
    </property>
</bean>

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven/>    

i got my controller method with usuarioService autowired and working. I get @modelattribute Usuario which was filled in form. I'm parsing to usuarioService the logged user id too ( i'm doing tests, so feel free to tell me the best approach in controller)

@RequestMapping(value="/atualizaCadastro",method = RequestMethod.POST)
public String updateCadastro(@ModelAttribute("usuario") Usuario usuario, HttpSession session){
    Usuario usuarioLogado = (Usuario)session.getAttribute("usuarioLogado");
    usuarioService.updateUsuario(usuarioLogado.getId(),usuario);
    return "redirect:home";
}

i got my service layer with @transactional annotation in its methods, usuarioDAO is autowired...

@Transactional
public void updateUsuario(Long usuarioId, Usuario usuarioUpdate) {
    // TODO Auto-generated method stub
    usuarioDAO.updateUsuario(usuarioId,usuarioUpdate);
}

i got my DAO method :

@Override
public void updateUsuario(Long usuarioId, Usuario usuarioUpdate) {
    // TODO Auto-generated method stub
    Session sessao = getSession().getCurrentSession();
    Usuario usuario = (Usuario)sessao.load(Usuario.class, usuarioId);
    usuario.setCelular(usuarioUpdate.getCelular());
    usuario.setDescricao(usuarioUpdate.getDescricao());
    sessao.update(usuario);
}

if i dont use "sessao.flush();" at the end of DAO method... my object its not being updated. Cant see any update statement in tomcat. As i planned to configure it i dont need .flush() right?!?!? where is the magic ( lol ) ?

Any suggestions? thanks in advance.

EDIT 1 )

I do use org.springframework.orm.hibernate4.support.OpenSessionInViewFilter

i also read we must set "flush_mode"(or something like this) to AUTO? this is really needed?

EDIT 2 )

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 

<hibernate-configuration>

 <session-factory>
   <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
   <property     name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
   <property name="hibernate.connection.url">jdbc:sqlserver://XXX.XX.XX.XX:1433;DatabaseName=WEBCLIENTES
   </property>
   <property name="hibernate.connection.username">XXXXXXX</property>
   <property name="hibernate.connection.password">YYYYYYY</property>
   <property name="hibernate.connection.pool_size">10</property>
   <property name="show_sql">true</property>
   <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>



   <mapping class="br.com.clarkemodet.clientes.model.Usuario" />
   <mapping class="br.com.clarkemodet.clientes.model.Cliente" />
   <mapping class="br.com.clarkemodet.clientes.model.Acesso" />
   <mapping class="br.com.clarkemodet.clientes.model.Historico" />
   <mapping class="br.com.clarkemodet.clientes.model.Inventor" />
   <mapping class="br.com.clarkemodet.clientes.model.NotaDebito" />
   <mapping class="br.com.clarkemodet.clientes.model.Titular" />
   <mapping class="br.com.clarkemodet.clientes.model.Processo" />

  </session-factory>

  </hibernate-configuration>

EDIT 3)

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Archetype Created Web Application</display-name>

 <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<!-- Spring Open Session In View Pattern filter -->
<filter>
<filter-name>hibernateFilter</filter-name>
  <filter-  class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
    <param-name>sessionFactoryBeanName</param-name>
    <param-value>sessionFactory</param-value>
</init-param>
</filter>

<!-- Spring/Hibernate filter mappings -->
 <filter-mapping>
 <filter-name>hibernateFilter</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <session-config>
  <session-timeout>5</session-timeout>
 </session-config>  

 </web-app>

EDIT 4 ) my spring-servlet.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

<context:annotation-config />
<context:component-scan base-package="br.com.clarkemodet.clientes" />

<bean id="jspViewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/pages/" />
    <property name="suffix" value=".jsp" />
</bean>

<mvc:resources mapping="/resources/**" location="/resources/frontend/" />
<mvc:annotation-driven />

<mvc:interceptors>
    <bean class="br.com.clarkemodet.clientes.interceptors.AutorizadorInterceptor" />
</mvc:interceptors>

</beans>
fferrandini
  • 101
  • 10
  • Please add your `hibernate.cfg.xml`. Flush-mode auto is the default when using spring. – M. Deinum Jul 10 '14 at 07:00
  • My guess is you have 2 instances of the service one transactional one not transactional. I would suspect that when you remove the `OpenSessionInViewFilter` you will get an exception stating that it cannot start a transaction. Make sure that the service instance that you use is in the same context as the `` else no transactions will be applied. – M. Deinum Jul 10 '14 at 07:09
  • i just posted my hibernate.cfg.xml. but how could i have 2 instances? i use a Service Interface, have one implementation and it's autowired to controller using interface. have Service and Transactional annotations set... how can i check for "service in same context as tx:annotation-driven"? i dont get it. thanks in advance man – fferrandini Jul 10 '14 at 11:50
  • You have a `ContextLoaderListener` and a `DispatcherServlet` judging from the snippets you posted at least your `` is loaded by the `ContextLoaderListener`. Now if you have a `` in the configuration loaded by the `ContextLoaderListener` that detects and instantiates beans. Now you probably have that same `` in the config loaded by the `DispatcherServlet`. That later will create a new isntance of your bean an as your `` isn't there there are now no more transactions. – M. Deinum Jul 10 '14 at 11:52
  • i just posted my web.xml and spring-servlet.xml so i should remove or add something to which xml? – fferrandini Jul 10 '14 at 12:28
  • `ContextLoaderListener` by default loads `applicationContext.xml`. `DispatcherServlet` by default loads `[servlet-name]-servlet.xml`, in your case `spring-servlet.xml` . – M. Deinum Jul 10 '14 at 12:30
  • if im not wrong i changed my DispatcherServlet to scan only controller s, in ContextLoaderListener i set to scan for service and DAO layers. but still not working. spring-servlet.xml : applicationContext.xml : – fferrandini Jul 10 '14 at 13:05
  • actually its working. but the update takes a few seconds to happen? well.. this question was solved. thanks @M.Deinum . Now i got another problem lol. – fferrandini Jul 10 '14 at 13:12
  • Use a proper connection pool. You are using the `DriverManagerDataSource` which isn't a connection pool but creates connections on demand. – M. Deinum Jul 10 '14 at 13:14
  • added c3p0. same behavior.. will try to figure it out. thanks @M.Deinum – fferrandini Jul 10 '14 at 13:49
  • but i think the problem is related on how i update the registry. the update statement appears in tomcat after i login another time with the same user. somehow the update is being hold till something happens. which i dont know... thanks – fferrandini Jul 10 '14 at 13:55

1 Answers1

0

Bom dia

  1. change sessao.load by sessao.get
  2. The updateUsuario method in your DAO class must be @Transactional too.
Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
  • hey.. but if my service layer method has @transactional, wouldnt the DAO method called inside it be transactional too? i will give a try and tell you if this worked. thanks in advance. – fferrandini Jul 09 '14 at 19:27
  • No really, If you want have the DAO within a Transaction **started** from the service, it must be @Transactional too. – Manuel Jordan Jul 09 '14 at 19:30
  • the same behavior after your instructions. i edited my post, i use openviewfilter from hibernate , some say you need to set flush property to AUTO, because default is NEVER.. is it right? – fferrandini Jul 09 '14 at 19:34
  • spring documentation: "NOTE: This filter will by default not flush the Hibernate Session, with the flush mode set to FlushMode.NEVER. It assumes to be used in combination with service layer transactions that care for the flushing: The active transaction manager will temporarily change the flush mode to FlushMode.AUTO during a read-write transaction, with the flush mode reset to FlushMode.NEVER at the end of each transaction. If you intend to use this filter without transactions, consider changing the default flush mode (through the "flushMode" property).".. i shouldnt worry about it, right? – fferrandini Jul 09 '14 at 19:37
  • 1. True but shouldn't be a problem. 2. No not necessary as long as there is a transaction in this case that is started form the service. – M. Deinum Jul 10 '14 at 06:59