SoFunction
Updated on 2025-03-08

Several methods of implementing ORM operation of MySQL in SpringBoot

Integrate mybatis in springboot framework using mybatis framework manipulation data

Steps to use:

Mybatis start dependency: complete the automatic configuration of mybatis object and place the object in the container.

    <dependencies>
<!--        webStarting dependency-->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--        mybaitisStarting dependency-->
        <dependency>
            <groupId></groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
<!--        mysqldrive-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
<!--        test-->
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

Specifies to include the xml file in the src/main/java directory into the classpath.

    <build>

<!--        resourcesPlugin-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId></groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

Create entity class Student

Create a Dao interface StudentDao, and create a method to query students.

/**
 * @Mapper: Tell MyBatis this to create a proxy object for this interface.
 *       Position: above the class.
 * **/
@Mapper
public interface StudentDao {
    Student selectById(@Param("stuId") Integer id);
}

Create the Mapper file, XML file corresponding to the Dao interface, and write SQL statements.

/**
 * @Mapper: Tell MyBatis this to create a proxy object for this interface.
 *       Position: above the class.
 * **/
@Mapper
public interface StudentDao {
    Student selectById(@Param("stuId") Integer id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-////DTD Mapper 3.0//EN"
        "/dtd/">
<mapper namespace="">
<!--    definitionsqlStatement-->
    <select  resultType="">
        select id,name,age from student where id=#{stuId}
    </select>
</mapper>

Create a servlet layer object, create a StudentService interface and its implementation class. Call the method of the dao object to complete the database operation.

package ;

public interface StudentService {
    Student queryStudent(Integer id);
}

package ;
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentDao studentDao;
    @Override
    public Student queryStudent(Integer id) {
        Student student=(id);
        return student;
    }
}

Create a Controller object and access the Service.

@Controller
public class StudentController {
    @Resource
    private StudentService studentService;

    @RequestMapping("/student/query")
    @ResponseBody
    public String queryStudent(Integer id){
        Student student = (id);
        return ();
    }
}

Write a file.

Configure the connection information of the database

=9001
-path=/orm
# Connect to the database-class-name=
=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
=root
=991231gao
 

1. The first method: @Mapper

@Mapper: Put it on the dao interface, and each interface needs to use this annotation.

/**
 * @Mapper: Tell MyBatis this to create a proxy object for this interface.
 *       Position: above the class.
 * **/
@Mapper
public interface StudentDao {
    Student selectById(@Param("stuId") Integer id);
}

2. The second way @MapperScan

/**
 * @MapperScan: Find Dao interface and Mapper files.
 *        basePackages: The package name of the dao interface
 * **/
@SpringBootApplication
@MapperScan(basePackages = {"",""})
public class Application {

    public static void main(String[] args) {
        (, args);
    }

}

3. The third method: manage the Mapper file and Dao interface separately

Now put the Mapper file in resources

  1. Create a subdirectory in the resources directory, such as mapper
  2. Put the mapper file into the mapper directory.
  3. In the file, specify the directory of the mapper file.
# Specify the location of the mapper file-locations=classpath:mapper/*.xml
# mybaiitis's log-impl=

Specify the directory in the resource directory and compile the files in the resource directory into the target directory.

<!--        resourcesPlugin-->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>

4. Transactions

Transactions in spring framework

Objects that manage transactions: Transaction manager (interfaces, interfaces have many implementation classes).

For example: use jdbc or mybatis to access the database, use transaction manager: DataSourceTransactionManager

Declarative transactions: In the XML configuration file or use annotations to explain the content of transaction control.

Control transactions: isolation level, propagation behavior, timeout time.

Transaction processing method

  • @Transactional in spring framework
  • The aspectj framework can declare transaction-controlled content in the XML configuration file.

Use transactions in springboot: Both of the above methods are OK.

  • Add @Transactional to the business method. After adding the annotation, the method has a transaction function.
  • Clearly add @EnableTransactionManager to the main startup class.
@SpringBootApplication

@EnableTransactionManagement

@MapperScan(value="")
public class Application {
   public static void main(String[] args) {
           (, args);
   }
}

example:

/**
 * @Transactional: It indicates that the method has transaction support
 *         Default: Use the isolation level of the library, REQUIRED propagation behavior; Timeout time -1
 *         Throw a runtime exception and roll back the transaction
 */
@Transactional
@Override
public int addStudent(Student student) {
    ("Business Methods AddStudent");
    int rows  =  (student);
    ("Execute SQL statement");

    // Throw a runtime exception, with the purpose of rolling back the transaction    //int m   = 10 / 0 ;

    return rows;
}

This is the end of this article about several methods of implementing ORM operation of MySQL in SpringBoot. For more related content on SpringBoot ORM operation of MySQL, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!