Table of Contents
Do not use SQL statements to add multiple tables in Springboot Mybatis-plus
Problems I encountered
Preparation work
Simulated in the test environment
Thinking breakdown:
Create A BrandDTO object with parameters
Simulates passing parameters to the background
Home Java javaTutorial How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables

Jun 02, 2023 am 11:07 AM
sql springboot mybatis-plus

Do not use SQL statements to add multiple tables in Springboot Mybatis-plus

The preparation work for the problems I encountered is broken down by simulating thinking in the test environment: Create a BrandDTO object simulation with parameters Passing parameters in the background

Problems I encountered

We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use Mybatis-plus- For tools like join, you can only configure the corresponding Mapper. Flexibility allows us to more flexibly modify the functions required by Party A.
But if I am going to do a very ordinary small project, which does not require any flexible changes, and I do not want to write SQL statements, I want to use Mybatis directly -plus function to add multi-table (one master and multiple copies) data, then what should I do?

Looking at the database, we can know that we have a product table, but productfor Product image, Product parameter and Product type are all one-to-many or many-to-one relationships, but I want our front-end to directly submit a form You can complete the addition of data in multiple tables. Multi-table operations are inevitable

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables

Preparation work

Because I have used mybatis before this operation -plus-join multi-table query operation, so I have generated a DTO entity class

@Data
public class BrandDTO {

    private Integer id;
    //类型表
    private String type;

    //商品表
    private String brandName;
    private String companyName;
    private String description;
    //图片链接表
    private List<Img> imgUrlList;
    //参数表
    private List<Parameter> parameterList;

}

In this class you will wonder: Why don’t I directly encapsulate a Brand entity object?
Because I have used this class to perform join table queries before, and put the parameters of each entity class separately (there is no duplicate name hhhh), and this class needs to be displayed, so I added the attributes of the Brand class as they are, and The tpye corresponding to Brand should be many (type) to one (Brand), so I only encapsulated one here, but since Brand has a one-to-many relationship with Img and Parameter, I encapsulated them into a list< object >, In this way we got something similar to an intermediate class

Simulated in the test environment

We might as well think about it, with such a class, we only need to separate the parameters To add to each table, we need to imagine that we get a BrandDTO object encapsulating data, and then disassemble it and use the methods of the respective mapper interfaces to insert the table behavior
(First the interface must inherit the corresponding BaseMapper<> ;, you can perform quick operations. Of course, if you have a corresponding adding method in the interface, you can also do it, but since we use mybatis-plus, why do we have to go back and write the adding method ourselves?)

So, after After several repeated experiments, I got the following test method:

 @Test
    public void addBrand(){
        Brand brand = new Brand();
        Type type = new Type();
        Img img = new Img();
        Parameter parameter = new Parameter();

        BrandDTO brandDTO = new BrandDTO();
        brandDTO.setBrandName("测试商品3");
        brandDTO.setCompanyName("厂家3");
        brandDTO.setDescription("这是第二个个测试");

        brandDTO.setType("第Ⅱ型");

        List<Img> imgs =new ArrayList<>();
        imgs.add(new Img("w/daw/daw/daww"));
        imgs.add(new Img("xxwdAWd/dawd/wx"));
        brandDTO.setImgUrlList(imgs);


        List<Parameter> parameters = new ArrayList<>();
        parameters.add(new Parameter("110","270*860*270",30,450));
        parameters.add(new Parameter("120","170*4350*720",990,5530));
        brandDTO.setParameterList(parameters);


        List<Img> imgUrlList = brandDTO.getImgUrlList();
        List<Parameter> parameterList = brandDTO.getParameterList();


        brand.setBrandName(brandDTO.getBrandName());
        brand.setCompanyName(brandDTO.getCompanyName());
        brand.setDescription(brandDTO.getDescription());
        brandMapper.insert(brand);

        Integer id = brand.getId();

        type.setBType(brandDTO.getType());
        type.setBId(id);
        typeMapper.insert(type);

        for (Parameter parameterl : parameterList) {
            parameter.setBModel(parameterl.getBModel());
            parameter.setBOutput(parameterl.getBOutput());
            parameter.setBSize(parameterl.getBSize());
            parameter.setBId(id);
            parameterMapper.insert(parameter);
        }

        for (Img imgl : imgUrlList) {
            img.setImgUrl(imgl.getImgUrl());
            img.setBrandId(id);
            imgMapper.insert(img);
        }

        System.out.println(id);

    }

Thinking breakdown:

Next, I will decompose and express each part of the method body

Create A BrandDTO object with parameters

First we simulated a BrandDTO object encapsulating various parameters:

        Type type = new Type();
        Img img = new Img();
        Parameter parameter = new Parameter();

        BrandDTO brandDTO = new BrandDTO();
        brandDTO.setBrandName("测试商品3");
        brandDTO.setCompanyName("厂家3");
        brandDTO.setDescription("这是第二个个测试");

        brandDTO.setType("第Ⅱ型");

        List<Img> imgs =new ArrayList<>();
        //此操作能成功是因为我在对应的对象中生成了除了id属性和外键属性的有参构造
        imgs.add(new Img("w/daw/daw/daww"));
        imgs.add(new Img("xxwdAWd/dawd/wx"));
        brandDTO.setImgUrlList(imgs);


        List<Parameter> parameters = new ArrayList<>();
        //此操作能成功是因为我在对应的对象中生成了除了id属性和外键属性的有参构造
        parameters.add(new Parameter("110","270*860*270",30,450));
        parameters.add(new Parameter("120","170*4350*720",990,5530));
        brandDTO.setParameterList(parameters);

This part is mainly the encapsulation of parameters, which is the work of the front end. Let us do the background work The server receives a BrandDTO object with parameters

Simulates passing parameters to the background

Takes out the corresponding parameters in each table

		//取出ImgUrlList和ParameterList()
		List<Img> imgUrlList = brandDTO.getImgUrlList();
        List<Parameter> parameterList = brandDTO.getParameterList();

		//单独封装brand对象
        brand.setBrandName(brandDTO.getBrandName());
        brand.setCompanyName(brandDTO.getCompanyName());
        brand.setDescription(brandDTO.getDescription());
        //调用对应Mapper接口的insert方法(或者你自己写的添加方法)
        brandMapper.insert(brand);
        //使用主键返回(要确保mybatis中设置了主键自增并且在各个实体类中声明了主键属性)
        Integer id = brand.getId();

After the above operations, we report to Brand A row of information is added to the table, and the primary key is returned.

So our other tables know the ID of the corresponding product, and can use this ID to define the foreign key ID in the table:

(Please note that in this test class, I injected the Mapper interface of each entity class that I need to use, so I can call the insert method)

		//向Type表中添加数据并指定外键(BrandID)的id
		type.setBType(brandDTO.getType());
        type.setBId(id);
        typeMapper.insert(type);
        //向Paramater表中添加数据并指定外键(BrandID)的id
        for (Parameter parameterl : parameterList) {
            parameter.setBModel(parameterl.getBModel());
            parameter.setBOutput(parameterl.getBOutput());
            parameter.setBSize(parameterl.getBSize());
            parameter.setBId(id);
            parameterMapper.insert(parameter);
        }
        //向Img表中添加数据并指定外键(BrandID)的id
        for (Img imgl : imgUrlList) {
            img.setImgUrl(imgl.getImgUrl());
            img.setBrandId(id);
            imgMapper.insert(img);
        }

Use a loop Add, we can add the data in the object to each table one by one. Next, we need to use the console to get the primary key id corresponding to the product we added:

System.out.println(id);

After that we run, what I got here The data is 3, and then we call the method of querying products by ID:
I am using Apifox here:

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables

It can be seen that our information has been inserted into the table The return value part is null because the multi-table query I wrote has some small bugs, but there is still data in the database. It can be seen that this test is successful. Next, just CV the code to the corresponding service. The controller layer can simulate passing in a Json object to check whether it is feasible!

The above is the detailed content of How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

Analysis of the impact of MySQL connection number on database performance Analysis of the impact of MySQL connection number on database performance Mar 16, 2024 am 10:09 AM

Analysis of the Impact of MySQL Connection Number on Database Performance With the continuous development of Internet applications, databases have become an important data storage and management tool to support application systems. In the database system, the number of connections is an important concept, which is directly related to the performance and stability of the database system. This article will start from the perspective of MySQL database, explore the impact of the number of connections on database performance, and analyze it through specific code examples. 1. What is the number of connections? The number of connections refers to the number of client connections supported by the database system at the same time. It can also be managed

The Purpose of SQL: Interacting with MySQL Databases The Purpose of SQL: Interacting with MySQL Databases Apr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

How to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

MySQL and SQL: Essential Skills for Developers MySQL and SQL: Essential Skills for Developers Apr 10, 2025 am 09:30 AM

MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

Basic concepts and usage analysis of SQL in Go language Basic concepts and usage analysis of SQL in Go language Mar 27, 2024 pm 05:30 PM

Basic concepts and usage of SQL in Go language SQL (StructuredQueryLanguage) is a language specially used to manage and operate relational databases. In Go language, we usually use SQL to perform database operations, such as querying data, inserting data, updating data, deleting data, etc. This article will introduce the basic concepts and usage of SQL in Go language, with specific code examples. 1. Connect to the database In Go language, we can use third-party libraries to connect data

MySQL: A Practical Application of SQL MySQL: A Practical Application of SQL May 08, 2025 am 12:12 AM

MySQL is popular because of its excellent performance and ease of use and maintenance. 1. Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2. Insert and query data: operate data through INSERTINTO and SELECT statements. 3. Optimize query: Use indexes and EXPLAIN statements to improve performance.

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

See all articles