search
HomeJavajavaTutorialHow to configure mybatis and transaction management in springboot

1. Configuration of spring boot and mybatis

1. First of all, all the dependencies required for spring boot to configure mybatis are as follows:

<!-- Spring Boot 启动父依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<!--以上内容放在dependencies标签外,如果你有已经有父标签,那将以上部分粘贴到父项目中-->
<!-- spring boot 项目启动必须引入的web依赖,以下内容放在dependency即可 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.5.1.RELEASE</version>
</dependency>       
 <!-- Spring Boot Mybatis 依赖 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.2.0</version>
</dependency>
 <!-- oracle的数据库驱动包 -->
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.4.0-atlassian-hosted</version>
</dependency>

Here we mainly talk about the above database driver package, oracle and Mysql introduces different dependencies, don’t forget them. If you forget to introduce it, a driver class not found exception will be reported.

2. Then, add the following content to the application.properties configuration file:

##数据库连接信息
spring.datasource.url=jdbc:oracle:thin:@//192.168.1.171:1521/orcl
spring.datasource.username=znxd
spring.datasource.password=znxd
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
##指向mapper的xml文件位置
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
##指向实体类的位置
mybatis.type-aliases-package=cloud.user.models.*

The content starting with spring.datasource above actually has There are many, for details, just enter them in the application.properties file and see what you can click on.   

By default, springboot will collect the information starting with spring.datasource, configure the DataSource object, and then configure the sqlSessionFactory and other related database connection configurations, so many other people will talk about what configuration class to write. , ones that I feel are unnecessary. (Configuring druid requires a @Bean)  

Of course, if it is particularly detailed, and the relevant configuration cannot be clicked through spring.datasource in the application.properties file , then you may need to configure classes or something.

mybatis.mapper-locations The location pointed to starts from src/main/resource. Classpath needs to be added in front. It points to the location where your mapper.xml file is placed. .

3. I am the entity class, mapper, etc. generated by mybatis through reverse engineering of the database table. First, I will post the specific placement structure of the project as follows:

How to configure mybatis and transaction management in springboot

The explanation for the above picture is as follows:

The startup class must be placed at the highest point in the project relative to other classes. As mentioned in the previous article, spring boot does not have the traditional spring project configuration

In the above picture, the service is placed higher than its implementation class. If there are two services A and B, and there are Aimpl and Bimpl in the implementation class, if Aimpl calls B, it may be in When starting the container, "a field named ‘B’ not found" appears. This error appears, indicating that the container scanning sequence is wrong.

The best solution to this situation is to put the service at a high place like I did. When the container starts, it scans the service first, and then scans the impl, so that it can be found when implementing class scanning. service, this error will not occur. Another solution is to add an additional annotation when introducing the service: @Lazy

@Autowired
@Lazy //这样就会延迟加载,上图不需要,这里只是解释这注解
LogsUserActiveMapper logsUserActiveMapper;

In short, if there is a relationship between calling and being called, you must remember that the callee must first be scanned into the spring boot built-in container , that is, the callee's package position should be placed higher (the positions must be at least equal).

4. A @Service annotation needs to be added to the service implementation class. This may not be necessary, I haven't tried it yet.  

5.spring boot mybatis In addition to these requirements, you also need to add an annotation @MapperScan to the startup class, as follows:

package cloud.kafka;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement //如果mybatis中service实现类中加入事务注解,需要此处添加该注解
@MapperScan("cloud.kafka.mapper")  //扫描的是mapper.xml中namespace指向值的包位置
public class KafkaLogApplication {
    public static void main(String[] args){
        SpringApplication.run(KafkaLogApplication.class, args);
    }
}

The following is the value of namespace in my mapper.xml

<mapper namespace="cloud.kafka.mapper.LogsUserActiveMapper" >

**This completes the configuration of mybatis.

2. Transaction configuration

is to add two annotations on the basis of mybatis

1. The required annotations are@ EnableTransactionManagement and @Transactional are two, they come from the following package:

spring-tx.jar

This package is actually in When configuring mybatis to introduce dependencies, they have been automatically introduced, which is the following:

 <!-- Spring Boot Mybatis 依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>

So as long as the above dependencies are introduced, the transaction does not need to introduce the package again,

2. First, Find your service implementation class and add the @Transactional annotation. If you add it to the class, then all methods of the class will be managed by transactions. If you add it to the method, then only the method conforms to the specific affairs. Of course, we usually add it to the method. Because only adding, deleting, and modifying will require transactions.

For example, the following method of inserting data adds a transaction:

@Override
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
public Integer add(Cbf_jtcy t) {
    return cbf_jtcyMapper.insert(t);
}

If you don’t know what is inside, you can check this article, spring, mybatis transaction management configuration and the use of @Transactional annotation

3. After configuration, the spring boot startup class must enable transactions, and the annotation used to enable transactions is @EnableTransactionManagement, as follows:

@SpringBootApplication
@EnableTransactionManagement 
@MapperScan("microservice.qssj.mapper")//必须加这个,不加报错,如果不加,也可以在每个mapper上添加@Mapper注释,并且这里还要多填一个注释,那个我忘了,我一直用这个注解
public class QssjServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(QssjServiceApplication.class, args);
    }
}

This is done Transaction configuration.

The above is the detailed content of How to configure mybatis and transaction management in springboot. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool