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)

Hot Topics

PHP Tutorial
1596
276
What are the BLOB and CLOB data types in SQL? What are the BLOB and CLOB data types in SQL? Aug 07, 2025 pm 04:22 PM

BLOBstoresbinarydatalikeimages,audio,orPDFsasrawbyteswithoutcharacterencoding,whileCLOBstoreslargetextsuchasarticlesorJSONusingcharacterencodinglikeUTF-8andsupportsstringoperations;2.Bothcanhandleuptogigabytesofdatadependingonthedatabase,butperforman

How to find the sum of a column in SQL? How to find the sum of a column in SQL? Aug 08, 2025 pm 05:54 PM

TofindthesumofacolumninSQL,usetheSUM()function,whichreturnsthetotalofallnumericvaluesinaspecifiedcolumnwhileignoringNULLs;1.Usebasicsyntax:SELECTSUM(column_name)ASaliasFROMtable_name;2.Ensurethecolumnhasnumericdatatoavoiderrors;3.ApplyWHEREtofilterro

How to get the first and last day of the year in SQL? How to get the first and last day of the year in SQL? Aug 11, 2025 pm 05:42 PM

ThefirstdayoftheyearisobtainedbyconstructingortruncatingtoJanuary1stofthegivenyear,andthelastdayisDecember31stofthesameyear,withmethodsvaryingbydatabasesystem;2.Fordynamiccurrentyeardates,MySQLusesDATE_FORMATorMAKEDATE,PostgreSQLusesDATE_TRUNCorDATE_

Understanding SQL Execution Context and Permissions Understanding SQL Execution Context and Permissions Aug 16, 2025 am 08:57 AM

SQL execution context refers to the identity or role when running SQL statements, which determine which resources and operation permissions can be accessed. Permission setting should follow the principle of minimum permissions, and common permissions include SELECT, INSERT, EXECUTE, etc. To troubleshoot permission issues, you need to confirm the login name, role permissions, EXECUTEAS settings and schema authorization. Performing context switching can be implemented through EXECUTEAS, but attention should be paid to user existence, permission granting and performance security impact. It is recommended to avoid arbitrarily assigning db_owner or sysadmin roles. The application account should only access necessary objects and be authorized through schema.

How to join a table to itself in SQL How to join a table to itself in SQL Aug 16, 2025 am 09:37 AM

Aself-joinisusedtocomparerowswithinthesametable,suchasinhierarchicaldatalikeemployee-managerrelationships,bytreatingthetableastwoseparateinstancesusingaliases,asdemonstratedwhenlistingemployeesalongsidetheirmanagers'nameswithaLEFTJOINtoincludetop-lev

What is the ALTER TABLE statement in SQL? What is the ALTER TABLE statement in SQL? Aug 08, 2025 pm 02:13 PM

TheALTERTABLEstatementisusedtomodifyanexistingtable’sstructurewithoutrecreatingit;1.AddanewcolumnusingADDCOLUMN;2.DropacolumnwithDROPCOLUMN,whichalsodeletesitsdata;3.RenameacolumnusingRENAMECOLUMN,withsyntaxconsistentinMySQL,SQLServer,andPostgreSQL;4

How to create a view in SQL How to create a view in SQL Aug 11, 2025 pm 12:40 PM

The syntax for creating a view is the CREATEVIEWview_nameASSELECT statement; 2. The view does not store actual data, but is based on the real-time query results of the underlying table; 3. The view can be modified using CREATEORREPLACEVIEW; 4. The view can be deleted through DROPVIEW; 5. The view is suitable for simplifying complex queries, providing data access control, and maintaining interface consistency, but attention should be paid to performance and logic, and finally ends with a complete sentence.

How to use FULL OUTER JOIN in SQL? How to use FULL OUTER JOIN in SQL? Aug 17, 2025 am 12:25 AM

AFULLOUTERJOINreturnsallrowsfrombothtables,withNULLswherenomatchexists;1)Itcombinesmatchingrecordsandincludesunmatchedrowsfrombothleftandrighttables;2)Itisusefulfordatareconciliation,mergereports,andidentifyingmismatches;3)Notalldatabasessupportitnat

See all articles