Spring事务管理

首先创建数据库mybatis并创建表customer。

创建工程并导入依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hubing</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.15</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.15</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.45</version>
        </dependency>
 
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.3.2</version>
        </dependency>
 
        <!--dbcp连接池-->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>

 导入依赖后在resources下创建database.properties添加数据库连接池配置。

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf-8
jdbc.user=root
jdbc.password=x5
jdbc.minIdle=45
jdbc.maxIdle=50
jdbc.initialSize=5
jdbc.maxActive=100
jdbc.maxWait=100
jdbc.removeAbandonedTimeout=180
jdbc.removeAbandoned=true

在resources下创建spring-mybatis.xml(名字可以随意写)添加数据库连接池并配置spring扫描包、配置sqlsession工厂、mapper动态代理和开启spring注解式事务。

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        "
>
    <context:component-scan base-package="com.hubing.*"/>
 
    <context:property-placeholder location="classpath:database.properties"/>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close" scope="singleton">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="${jdbc.initialSize}"/>
        <property name="maxActive" value="${jdbc.maxActive}"/>
        <property name="maxIdle" value="${jdbc.maxIdle}"/>
        <property name="minIdle" value="${jdbc.minIdle}"/>
        <property name="maxWait" value="${jdbc.maxWait}"/>
        <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}"/>
        <property name="removeAbandoned" value="${jdbc.removeAbandoned}"/>
    </bean>
    <!--配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--<property name="configLocation" value="classpath:mybatis-config.xml"/>-->
        <property name="typeAliasesPackage" value="com.hubing.hb.pojo"></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>
    <!--扫描映射文件(mapper动态代理)-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.hubing.hb.dao"/>
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
 
    <!-- 开启注解 -->
    <mvc:annotation-driven/>
    <!--transaction-manager="transactionManager"一定要加上,否则会报错,该配置是以事物的方式开启注解-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

 创建Customer实体类添加get/set,toString方法。

package com.hubing.hb.pojo;
 
public class Customer {
    private Integer id;
    private String username;
    private String jobs;
    private String phone;
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getJobs() {
        return jobs;
    }
 
    public void setJobs(String jobs) {
        this.jobs = jobs;
    }
 
    public String getPhone() {
        return phone;
    }
 
    public void setPhone(String phone) {
        this.phone = phone;
    }
 
    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", jobs='" + jobs + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}

创建dao层。

package com.hubing.hb.dao;
 
import com.hubing.hb.pojo.Customer;
 
import java.util.List;
 
public interface CustomerDao {
 
    public List<Customer> query();
 
    public void add(Customer customer);
 
}

在resources下创建mapper文件夹并在mapper下创建customerMapper.xml(注意:namespace的接口和方法的返回值类型)。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<!-- 1.namespace:接口的一个路径 ,2.id :接口下抽象方法名
    3.接口的返回值和resultType 对应上 ,4接口的参数 对应上-->
<mapper namespace="com.hubing.hb.dao.CustomerDao">
    <select id="query" resultType="com.hubing.hb.pojo.Customer">
        select * from customer
    </select>
    <insert id="add">
        insert into customer (username , jobs , phone) values (#{username} , #{jobs} , #{phone})
    </insert>
</mapper>
 

创建service层(业务层)。

package com.hubing.hb.service;
 
import com.hubing.hb.pojo.Customer;
import com.hubing.hb.pojo.Student;
 
import java.util.List;
 
public interface CustomerService {
    public List<Customer> query();
 
    public void add(Customer customer);
 
}

创建serviceimpl(业务层的接口实现类)(注意:@Service是将实现类添加到spring组件中)(加入@Transactional注解使用spring事务管理)。

package com.hubing.hb.service.impl;
 
import com.hubing.hb.dao.CustomerDao;
import com.hubing.hb.dao.StudentDao;
import com.hubing.hb.pojo.Customer;
import com.hubing.hb.pojo.Student;
import com.hubing.hb.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.List;
 
@Service
public class CustomerServiceImpl implements CustomerService {
 
    @Autowired
    CustomerDao dao;
 
    @Autowired
    StudentDao studentDao;
 
    public List<Customer> query() {
        List<Customer> list = dao.query();
        return list;
    }
 
    @Transactional
    public void add(Customer customer) {
        dao.add(customer);    
    }
 
}

创建controller层实现调用。

package com.hubing.hb.controller;
 
import com.hubing.hb.pojo.Customer;
import com.hubing.hb.pojo.Student;
import com.hubing.hb.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
 
import java.util.List;
 
@Controller
public class CustomerController {
    @Autowired
    CustomerService service;
 
    public String query() {
        List<Customer> list = service.query();
        System.out.println(list);
        return null;
    }
 
    public String add(Customer customer) {
        service.add(customer);
        return null;
    }
}

最后创建测试类测试(getBean("customerController是由controller层中的@Controller进行装配"))。

package com.wang;
 
import com.wang.hxci.controller.CustomerController;
import com.wang.hxci.pojo.Customer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class TestDemo {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml");
        CustomerController controller = (CustomerController)context.getBean("customerController");
        Customer customer =new Customer();
        customer.setUsername("张三");
        customer.setPhone("12222222");
        customer.setJobs("java");
        controller.add(customer);
        controller.query();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值