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

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, 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

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
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft