spring Transactional

Posted popcorn丫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring Transactional相关的知识,希望对你有一定的参考价值。

实体类:

Log:

 1 package com.bxw.vo;
 2 
 3 import javax.persistence.Entity;
 4 import javax.persistence.GeneratedValue;
 5 import javax.persistence.Id;
 6 import javax.persistence.Table;
 7 
 8 import org.hibernate.annotations.GenericGenerator;
 9 
10 @Entity
11 @Table(name="t_log")
12 public class Log {
13     private int id;
14     private String msg;
15     
16     @Id
17     @GenericGenerator(name="generator", strategy="increment")  
18     @GeneratedValue(generator="generator")
19     public int getId() {
20         return id;
21     }
22     public void setId(int id) {
23         this.id = id;
24     }
25     public String getMsg() {
26         return msg;
27     }
28     public void setMsg(String msg) {
29         this.msg = msg;
30     }
31     
32     
33 }

因为该实体类名与表名不同,所以添加

@Table(name="t_log")

User:
 1 package com.bxw.vo;
 2 
 3 import javax.persistence.Entity;
 4 import javax.persistence.GeneratedValue;
 5 import javax.persistence.Id;
 6 
 7 import org.hibernate.annotations.GenericGenerator;
 8 
 9 
10 @Entity
11 public class User {
12     private int id;
13     private String name;
14     
15     @Id
16     @GenericGenerator(name="generator", strategy="increment")  
17     @GeneratedValue(generator="generator")
18     public int getId() {
19         return id;
20     }
21     public void setId(int id) {
22         this.id = id;
23     }
24     
25     public String getName() {
26         return name;
27     }
28     public void setName(String name) {
29         this.name = name;
30     }
31     
32     
33 }

 

Dao:

1 package com.bxw.datasourse.dao;
2 
3 import com.bxw.vo.Log;
4 
5 public interface LogDao {
6     public void save(Log log);
7 }
package com.bxw.datasourse.dao;

import com.bxw.vo.User;

public interface UserDao {
    public void saveUser(User user);
}

 

DaoImpl:

package com.bxw.datasourse.daoimpl;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.bxw.datasourse.dao.LogDao;
import com.bxw.vo.Log;

@Repository("logDao")
public class LogDaoImpl implements LogDao{
    private SessionFactory sessionFactory;
    
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    @Resource
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void save(Log log) {
        Session session = sessionFactory.getCurrentSession();
        session.save(log);
    }

}
package com.bxw.datasourse.daoimpl;
 

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.bxw.datasourse.dao.UserDao;
import com.bxw.vo.User;
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    private SessionFactory sessionFactory;
    
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    @Resource(name="sessionFactory")
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void saveUser(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.save(user);
    }

}

 

Service:

1 package com.bxw.service;
2 
3 import com.bxw.vo.User;
4 
5 public interface UserService {
6     public void save(User user);
7 }

 

ServiceImpl:
 1 package com.bxw.serviceimpl;
 2 
 3 import javax.annotation.Resource;
 4 import javax.transaction.Transactional;
 5 
 6 import org.springframework.stereotype.Service;
 7 
 8 import com.bxw.datasourse.dao.LogDao;
 9 import com.bxw.datasourse.dao.UserDao;
10 import com.bxw.service.UserService;
11 import com.bxw.vo.Log;
12 import com.bxw.vo.User;
13 
14 @Service("userService")
15 public class UserServiceImpl implements UserService{
16     private UserDao userDao;
17     private LogDao logDao;
18     
19     public UserDao getUserDao() {
20         return userDao;
21     }
22     @Resource
23     public void setUserDao(UserDao userDao) {
24         this.userDao = userDao;
25     }
26 
27     public LogDao getLogDao() {
28         return logDao;
29     }
30     @Resource
31     public void setLogDao(LogDao logDao) {
32         this.logDao = logDao;
33     }
34     @Transactional
35     public void save(User user) {
36         userDao.saveUser(user);
37         Log log = new Log();
38         log.setMsg(user.getName()+"has been saved!");
39         logDao.save(log);
40     }
41 
42 }
@Transactional:添加事务。添加事务的时候一定要在service层添加,因为如果添加在dao层,会产生事务不同步的情况。假如业务要求是先添加一个用户,然后添加日志信息。事务如果添加在dao层,会出现添加用户失败,而日志记录的情况。

配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:cache="http://www.springframework.org/schema/cache"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context.xsd  
    http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans.xsd  
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx.xsd  
    http://www.springframework.org/schema/jdbc  
    http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd  
    http://www.springframework.org/schema/cache  
    http://www.springframework.org/schema/cache/spring-cache-3.1.xsd  
    http://www.springframework.org/schema/aop  
    http://www.springframework.org/schema/aop/spring-aop.xsd  
    http://www.springframework.org/schema/util  
    http://www.springframework.org/schema/util/spring-util.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.bxw.*"></context:component-scan>
    <!-- datasource -->
    <bean id="myJdbcProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>classpath:jdbc.properties</value>
        </property>
    </bean>
    <bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    
    <bean id="sessionFactory" 
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="datasource"></property>
        <property name="packagesToScan" value="com.bxw.vo" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.mysqlDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    
    <!-- spring管理hibernate事务 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
    
</beans>

自动扫描包中的组件;配置datasource;配置sessionFactory;将sessionFactory注入事务管理。自动扫描事务,及配置了@Transactional注解的方法。

 

Test:

package com.bxw.serviceimpl;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bxw.service.UserService;
import com.bxw.vo.User;

public class UserServiceImplTest {
    public static void main(String[] args) {
        User user = new User();
        user.setName("Han meimei");
        
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) ac.getBean("userService");
        userService.save(user);
    }
}

 
















以上是关于spring Transactional的主要内容,如果未能解决你的问题,请参考以下文章

Spring中的@Transactional

Spring @Transactional private

Spring @Transactional原理

即使 @Transactional 放置在服务层中,Spring boot JPA 存储库也会提交代码

Spring事务:@Transactional

Spring 事务注解@Transactional