2014-11-06 4 views
0

Я создал простое приложение пружины, где есть таблица счетов с номером счета (первичный ключ), тип счета, балансSpring Hibernate транзакции: данные не получает сохранены

Когда я когда-либо попытаться обновить данные, не происходит, оно все еще показывает старое значение.

Вот мой конфигурационный файл.

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

    <context:annotation-config/> 

    <bean id="dataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 
     <property name="url" value="jdbc:mysql://localhost:3306/jlcindiadb"/> 
     <property name="username" value="root"/> 
     <property name="password" value="123"/> 
    </bean> 

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 

     <property name="dataSource" ref="dataSource"/>  
     <property name="mappingResources"> 
      <list> 
       <value>com/jlcindia/spring/Account.hbm.xml</value> 
      </list> 
     </property> 
    <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 
       <prop key="hibernate.show_sql">true</prop> 
       <prop key="hibernate.hbm2ddl.auto" >update</prop> 
      </props> 
     </property> 
    </bean>   

     <bean id="hibernateTemp" class="org.springframework.orm.hibernate3.HibernateTemplate" 
        autowire="constructor"/>  

     <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" autowire="constructor"/> 

     <bean id="accdao" class="com.jlcindia.spring.HibernateAccountDAO"/>      
     <bean id="as" class="com.jlcindia.spring.AccountServiceImpl"/> 

    </beans>  

Фрагмент для депонирования.

public void deposit(int accno, double amt) { 
    TransactionDefinition txDef= new DefaultTransactionDefinition(); 
    TransactionStatus ts= txManager.getTransaction(txDef); 
    Account acc=htemp.load(Account.class,accno,LockMode.READ); 
    double cbal=acc.getBal();  
    acc.setBal(cbal+amt); 
    htemp.update(acc); 
    txManager.commit(ts);  
} 

Изначально моя таблица содержит следующие записи:

  Account  Account Balance 
      No   Type 

Account1: 101   SA  1000 

Account2: 102   SA  2000 

Account3: 103   CA  3000 

Теперь об обновлении данных. То есть после внесения данных он по-прежнему показывает одинаковый баланс. Почему такое поведение? Пожалуйста, объясните ..

Update:

класса, содержащий функцию Deposit.

import org.hibernate.LockMode; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.orm.hibernate3.HibernateTemplate; 
import org.springframework.orm.hibernate3.HibernateTransactionManager; 
import org.springframework.transaction.TransactionDefinition; 
import org.springframework.transaction.TransactionStatus; 
import org.springframework.transaction.support.DefaultTransactionDefinition; 

public class HibernateAccountDAO implements AccountDAO{ 

@Autowired 
HibernateTemplate htemp=null; 

@Autowired 
HibernateTransactionManager txManager=null; 

@Override 
public void deposit(int accno, double amt) { 
    TransactionDefinition txDef= new DefaultTransactionDefinition(); 
    TransactionStatus ts= txManager.getTransaction(txDef); 
    Account acc=htemp.load(Account.class,accno,LockMode.READ); 
    double cbal=acc.getBal(); 
    //int cbal=(int)bal; 

    acc.setBal(cbal+amt); 
    htemp.update(acc);  
    txManager.commit(ts); 
    //System.out.println("Acc get Account number "+acc.getAccno()); 
    //System.out.println("Acc get Account type "+acc.getAtype()); 
    //System.out.println("Acc get Balance "+acc.getBal()); 
} 


@Override 
public void withdraw(int accno, double amt) { 
    TransactionDefinition txDef= new DefaultTransactionDefinition(); 
    TransactionStatus ts= txManager.getTransaction(txDef); 
    Account acc=htemp.load(Account.class,accno,LockMode.READ); 
    double cbal=acc.getBal(); 
    if(cbal>500+amt){ 
     acc.setBal(cbal-amt); 
     htemp.update(acc);   
    }else{ 
     throw new InSufficientFundsException();   
    } 
    txManager.commit(ts); 

} 

@Override 
public void fundsTransfer(int saccno, int daccno, double amt) { 
    TransactionDefinition txDef= new DefaultTransactionDefinition(); 
    TransactionStatus ts= txManager.getTransaction(txDef); 
    try{ 
    Account acc1=htemp.load(Account.class,daccno,LockMode.READ); 
    double dcbal=acc1.getBal(); 
    acc1.setBal(dcbal+amt); 
    htemp.update(acc1); 

    Account acc2=htemp.load(Account.class,saccno,LockMode.READ); 
    double scbal=acc2.getBal(); 
    if(scbal>=500+amt){ 
     acc2.setBal(scbal-amt);   
     htemp.update(acc2); 
    }else{ 
     throw new InSufficientFundsException(); 
    } 
    txManager.commit(ts); 

    }catch(Exception e){ 
     txManager.rollback(ts); 
     e.printStackTrace(); 
    } 
} 

@Override 
public double getBalance(int accno) { 
    TransactionDefinition txDef= new DefaultTransactionDefinition(); 
    TransactionStatus ts= txManager.getTransaction(txDef); 
    Account acc=htemp.load(Account.class,accno,LockMode.READ); 
    double cbal=acc.getBal(); 
    return cbal;   
} 

}

ответ

0

Похоже, вы не предоставили сессионный завод в спящем режиме шаблона и менеджер транзакций. Попробуйте снова протестировать, изменив конкретную часть xml, как показано ниже? :

<bean id="hibernateTemp" class="org.springframework.orm.hibernate3.HibernateTemplate" 
     autowire="constructor"/> 
    <property name="sessionFactory" ref="sessionFactory"></property> 
</bean>     

<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" 
     autowire="constructor"> 
    <property name="sessionFactory" ref="sessionFactory"></property> 
</bean> 

Мой моделирование сниппет:

Resource r=new ClassPathResource("applicationContext.xml"); 
BeanFactory factory=new XmlBeanFactory(r); 
HibernateTemplate template = (HibernateTemplate) factory.getBean("template"); 
HibernateTransactionManager txManager = (HibernateTransactionManager) factory.getBean ("txManager"); 
TransactionDefinition txDef= new DefaultTransactionDefinition(); 
TransactionStatus ts= txManager.getTransaction(txDef); 
Employee acc=template.load(Employee.class,114,LockMode.READ);  
acc.setName("varun"); 
template.update(acc); 
txManager.commit(ts); 
+0

Спасибо за проявленный интерес, я реализовал выше предложение. но все же он дает тот же результат. То есть данные по-прежнему не сохраняются. – User27854

+0

Если ваш фасон фабрики сеансов называется 'sessionFactory', Hibernate автоматически подбирает его. Это только, если ваш bean-компонент называется чем-то другим, который вы должны указать. – JamesENL

+0

@JamesMassey, хорошо, моя проблема все еще существует, любая идея, как это сделать. – User27854

Смежные вопросы