其他分享
首页 > 其他分享> > Spring 事务基于注解和xml方式

Spring 事务基于注解和xml方式

作者:互联网

文章目录

基于注解方式的Spring事务配置

1 创建表结构

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
  `id` int NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
  `money` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ----------------------------
-- Records of account
-- ----------------------------
BEGIN;
INSERT INTO `account` VALUES (1, 'lucy', 1000);
INSERT INTO `account` VALUES (2, 'mary', 1000);
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

2 创建实体类

package com.ccb.po;

public class Account {
    private Integer id;
    private String name;
    private Integer money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getMoney() {
        return money;
    }

    public void setMoney(Integer money) {
        this.money = money;
    }
}

3 创建Dao

package com.ccb.dao;

public interface AccountDao {
    void addMoney();
    void minusMoney();
}

4 创建DaoImpl

package com.ccb.dao.impl;

import com.ccb.dao.AccountDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository("accountDaoImpl")
public class AccountDaoImpl implements AccountDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void addMoney() {
        String sql = "update account set money = money+? where name = ?";
        jdbcTemplate.update(sql,100,"mary");
    }

    @Override
    public void minusMoney() {
        String sql = "update account set money = money-? where name = ?";
        jdbcTemplate.update(sql,100,"lucy");
    }
}

5 创建Service

package com.ccb.service;

public interface AccountService {
    void accountMoney();

    void addMoney();
    void minusMoney();
}

6 创建SrviceImpl

package com.ccb.service.impl;

import com.ccb.dao.UserDao;
import com.ccb.po.User;
import com.ccb.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    @Override
    public void addUser(User user) {
        userDao.addUser(user);
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }

    @Override
    public void deleteUser(User user) {
        userDao.deleteUser(user);
    }

    @Override
    public User getUser(User user) {
        return userDao.getUser(user);
    }

    @Override
    public List<User> getListUser() {
        return userDao.getListUser();
    }

    @Override
    public void batchAddUser(List<Object[]> objects) {
        userDao.batchAddUser(objects);
    }

    @Override
    public void batchUpdateUser(List<Object[]> objects) {
        userDao.batchUpdate(objects);
    }

    @Override
    public void batchDeleteUser(List<Object[]> objects) {
        userDao.batchDeleteUser(objects);
    }
}

7 创建TxConfig

package com.ccb.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@ComponentScan(basePackages = "com.ccb")    //开启组件扫描
@Configuration  //配置类
@EnableTransactionManagement    //开启事务
public class TxConfig {
    //创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://192.168.1.4:3306/db_user");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    //创建JdbcTemplate
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        //到ioc容器中根据类型找到DataSource
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //注入dataSource
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //创建事务管理器
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}

8 创建Test

package com.ccb.user;


import com.ccb.config.TxConfig;
import com.ccb.po.User;
import com.ccb.service.AccountService;
import com.ccb.service.UserService;
import com.ccb.service.impl.AccountServiceImpl;
import com.ccb.service.impl.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class UserTest {

    @Test
    public void testTxConfig(){
        ApplicationContext  applicationContext = new AnnotationConfigApplicationContext(TxConfig.class);
        AccountService accountService = applicationContext.getBean("accountServiceImpl", AccountService.class);
        accountService.accountMoney();

    }
}

基于xml方式Spring事务配置

1 创建表结构

同上注解方式

2 创建实体类

同上注解方式

3 创建Dao

同上注解方式

4 创建DaoImpl

同上注解方式

5 创建Service

同上注解方式

6 创建ServiceImpl

同上注解方式

7 beans.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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.ccb"></context:component-scan>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://192.168.1.4:3306/db_user"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

8 创建Test

package com.ccb.user;


import com.ccb.config.TxConfig;
import com.ccb.po.User;
import com.ccb.service.AccountService;
import com.ccb.service.UserService;
import com.ccb.service.impl.AccountServiceImpl;
import com.ccb.service.impl.UserServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class UserTest {
    @Test
    public void testTx(){
        ApplicationContext  applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        AccountService accountService = applicationContext.getBean("accountServiceImpl", AccountService.class);
        accountService.accountMoney();
    }
}

文章目录

标签:xml,Spring,void,创建,import,com,public,注解,ccb
来源: https://blog.csdn.net/chengwen_/article/details/118400355