Enterprise spring boot tutorial spring boot enable declarative transaction

Keywords: Programming Mybatis Spring MySQL SpringBoot

springboot is very simple to start a transaction, only one annotation is needed @Transactional Just fine. Because in springboot, events have been enabled for jpa, jdbc and mybatis by default. When they are introduced, things will be enabled by default. Of course, if you need to use other orm, such as beatlsql, you need to configure the relevant transaction manager yourself.

Preparation stage

The code in the above article is an example, that is, spring boot integrates mybatis. The previous article implemented the data access layer of mybatis based on annotations. This article implemented it based on xml and opened declarative transactions.

Environmental dependence

To introduce the mybatis startup dependency in the pom file:

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
</dependency>

Introduce mysql dependency

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.29</version>
        </dependency>

Initialize database script

-- create table `account`
# DROP TABLE `account` IF EXISTS
CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `money` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `account` VALUES ('1', 'aaa', '1000');
INSERT INTO `account` VALUES ('2', 'bbb', '1000');
INSERT INTO `account` VALUES ('3', 'ccc', '1000');

Configure data sources

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath*:mybatis/*Mapper.xml
mybatis.type-aliases-package=com.forezp.entity

By configuring mybatis.mapper-locations to indicate the location of mapper's xml file, I put it under the resources/mybatis file. mybatis.type-aliases-package to indicate the package of the entity mapped with the database.

After the above steps, springboot can access the database through mybatis.

Create entity class

public class Account {
    private int id ;
    private String name ;
    private double money;
 
    getter..
    setter..
 
  }

Spring Cloud large enterprise distributed microservice Cloud Architecture source code Please add Penguin request: 17917433880

Posted by jasonman1 on Sat, 07 Dec 2019 04:24:59 -0800