MyBaits的注解开发

news2024/11/17 3:28:54

为什么要用MyBaits注解开发?

前面介绍了MyBatis的基本用法、关联映射、动态SQL和缓存机制等知识,所有的配置都是基于XML文件完成的,但在实际开发中,大量的XML配置文件的编写是非常繁琐的,为此,MyBatis提供了更加简便的基于注解的配置方式。

基于注解的单表增删改查 

代码示例:

1.pom.xml引入项目需要的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>_20230503</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

2.建表∶在mybatis数据库中创建名为tb_worker的数据表,同时预先插入几条测试数据。

3.根据数据库的表结构,创建实体类Worker

package cn.hdc.pojo;

public class Worker {
    private int id;
    private String name;
    private int age;
    private String sex;
    private String worker_id;

    @Override
    public String toString() {
        return "Worker{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", worker_id='" + worker_id + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getWorker_id() {
        return worker_id;
    }

    public void setWorker_id(String worker_id) {
        this.worker_id = worker_id;
    }
}

 4.创建WorkerMapper接口声明要实现的方法:

package cn.hdc.mapper;

import cn.hdc.pojo.Worker;
import org.apache.ibatis.annotations.*;

public interface WorkerMapper {
    @Select("select * from tb_worker where id=#{id}")
    public Worker findWorker(int id);

    @Insert("insert into tb_worker values (null,#{name},#{age},#{sex},#{worker_id})")
    public int insertWorker(Worker worker);

    @Update("update tb_worker set name=#{name},age=#{age} where id=#{id}")
    public int updateWorker(Worker worker);

    @Delete("delete from tb_worker where id=#{id}")
    public int deleteWorker(int id);


    @Select("select * from tb_worker where id=#{param1} and name=#{param2}")
    public Worker selectWorkerByIdAndName(@Param("param1") int id, @Param("param2") String name);

}

5.创建MyBatisUtils工具类

package cn.hdc.utils;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
import java.io.IOException;
import java.io.Reader;
 
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
 
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
}

6.创建db.properties

driver.driver=com.mysql.cj.jdbc.Driver
driver.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver.username=root
driver.password=666666

7.创建mybaits-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 环境配置 -->
    <!-- 加载类路径下的属性文件 -->
    <properties resource="db.properties"/>

    <!-- 数据库连接相关配置 ,db.properties文件中的内容-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver.driver}"/>
                <property name="url" value="${driver.url}"/>
                <property name="username" value="${driver.username}"/>
                <property name="password" value="${driver.password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <package name="cn.hdc.mapper"/>
    </mappers>
</configuration>

8.创建测试类WorkerMapperTest

package cn.hdc.mapper;

import cn.hdc.pojo.Worker;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class WorkerMapperTest {
    private WorkerMapper workerMapper;
    private SqlSession session;

    @Before
    public void setUp() throws Exception {
        session = MybatisUtils.getSession();
    }

    @After
    public void tearDown() throws Exception {
        session.commit();
        session.close();
    }

    @Test
    public void findWorker() {
        workerMapper = session.getMapper(WorkerMapper.class);
        Worker worker = workerMapper.findWorker(1);
        System.out.println(worker);
    }

    @Test
    public void insertWorker() {
        workerMapper = session.getMapper(WorkerMapper.class);
        Worker worker = new Worker();
        worker.setName("赵六");
        worker.setAge(23);
        worker.setSex("男");
        worker.setWorker_id("1004");
        int i = workerMapper.insertWorker(worker);
        if (i > 0) {
            System.out.println("插入成功!");
        } else {
            System.out.println("插入失败!");
        }
    }

    @Test
    public void updateWorker() {
        workerMapper = session.getMapper(WorkerMapper.class);
        Worker worker = new Worker();
        worker.setName("李华");
        worker.setAge(30);
        worker.setId(4);
        int ret = workerMapper.updateWorker(worker);
        if (ret > 0) {
            System.out.println("修改成功!");
        } else {
            System.out.println("修改失败!");
        }
    }

    @Test
    public void deleteWorker() {
        workerMapper = session.getMapper(WorkerMapper.class);
        int ret = workerMapper.deleteWorker(4);
        if (ret > 0) {
            System.out.println("删除成功!");
        } else {
            System.out.println("删除失败!");
        }
    }

    @Test
    public void selectWorkerByIdAndName() {
        workerMapper = session.getMapper(WorkerMapper.class);
        Worker worker = workerMapper.selectWorkerByIdAndName(3, "王五");
        System.out.println(worker);
    }
}

9.项目结构:

10.@Param注解说明:

在MyBatis中,@param注解用于为SQL语句中的参数提供名称和值。它将参数名称和值映射到SQL语句中的占位符(?)或具名参数上。当使用动态SQL时,@param注解还可以帮助 MyBatis 明确哪些参数是必须提供的,哪些是可选的。使用@param注解可以提高代码可读性和维护性,并且可以避免潜在的bug。 

基于注解的关联查询

—对一查询:

代码示例:

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>_20230503</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

2.建库,建表:

tb_person表:

CREATE TABLE `tb_person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` varchar(8) DEFAULT NULL,
  `card_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `card_id` (`card_id`),
  CONSTRAINT `tb_person_ibfk_1` FOREIGN KEY (`card_id`) REFERENCES `tb_idcard` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4

tb_idcard表:

CREATE TABLE `tb_idcard` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(18) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4

3.创建实体类:Person

package cn.hdc.pojo;

public class Person {
    private int id;
    private String name;
    private int age;
    private String sex;
    private IdCard idCard;

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                ", idCard=" + idCard +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public IdCard getIdCard() {
        return idCard;
    }

    public void setIdCard(IdCard idCard) {
        this.idCard = idCard;
    }
}

4.创建实体类:IdCard:

package cn.hdc.pojo;

public class IdCard {
    private int id;
    private String code;

    @Override
    public String toString() {
        return "IdCard{" +
                "id=" + id +
                ", code='" + code + '\'' +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}

5.创建接口IdCardMapper:

package cn.hdc.mapper;

import cn.hdc.pojo.IdCard;
import org.apache.ibatis.annotations.Select;

public interface IdCardMapper {
    @Select("select * from tb_idCard where id = #{id}")
    public IdCard selectIdCardById(int id);
}

6.创建接口PersonMapper:

package cn.hdc.mapper;

import cn.hdc.pojo.Person;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface PersonMapper {
    @Select("select * from tb_person where id=#{id}")
    @Results(@Result(
            column = "card_id",
            property = "idCard",
            one = @One(select = "cn.hdc.mapper.IdCardMapper.selectIdCardById")
    ))
    public Person selectPersonById(int id);
}

7.创建MyBatisUtils工具类:

package cn.hdc.utils;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
import java.io.IOException;
import java.io.Reader;
 
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
 
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
}

8.db.properties:

driver.driver=com.mysql.cj.jdbc.Driver
driver.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver.username=root
driver.password=666666

9.mybaits-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 环境配置 -->
    <!-- 加载类路径下的属性文件 -->
    <properties resource="db.properties"/>

    <!-- 数据库连接相关配置 ,db.properties文件中的内容-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver.driver}"/>
                <property name="url" value="${driver.url}"/>
                <property name="username" value="${driver.username}"/>
                <property name="password" value="${driver.password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <package name="cn.hdc.mapper"/>
    </mappers>
</configuration>

10.创建PersonMapperTest,测试类:

package cn.hdc.mapper;

import cn.hdc.pojo.Person;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class PersonMapperTest {
    private SqlSession session;
    private PersonMapper personMapper;

    @Before
    public void setUp() throws Exception {
        session = MybatisUtils.getSession();
    }

    @After
    public void tearDown() throws Exception {
        session.commit();
        session.close();
    }

    @Test
    public void selectPersonById() {
        personMapper = session.getMapper(PersonMapper.class);
        Person person = personMapper.selectPersonById(1);
        System.out.println(person);
    }
}

11.项目结构:

12.运行结果:

一对多查询:

代码示例:

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>_20230503</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

2.db.properties

driver.driver=com.mysql.cj.jdbc.Driver
driver.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver.username=root
driver.password=666666

3.mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 环境配置 -->
    <!-- 加载类路径下的属性文件 -->
    <properties resource="db.properties"/>

    <!-- 数据库连接相关配置 ,db.properties文件中的内容-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver.driver}"/>
                <property name="url" value="${driver.url}"/>
                <property name="username" value="${driver.username}"/>
                <property name="password" value="${driver.password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <package name="cn.hdc.mapper"/>
    </mappers>
</configuration>

4.MyBaitsUtils工具类:

package cn.hdc.utils;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
import java.io.IOException;
import java.io.Reader;
 
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
 
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
}

5.建库建表:

tb_user表:

CREATE TABLE `tb_user` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) DEFAULT NULL,
  `address` varchar(256) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4

tb_orders表:

CREATE TABLE `tb_orders` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `number` varchar(32) NOT NULL,
  `user_id` int(32) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `tb_orders_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `tb_user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4

6.创建实体类:User:

package cn.hdc.pojo;

import java.util.List;

public class User {
    private int id;
    private String username;
    private String address;
    private List<Orders> ordersList;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                ", ordersList=" + ordersList +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public List<Orders> getOrdersList() {
        return ordersList;
    }

    public void setOrdersList(List<Orders> ordersList) {
        this.ordersList = ordersList;
    }
}

7.创建实体类:Orders:

package cn.hdc.pojo;

public class Orders {
    private int id;
    private String number;
    private int userId;

    @Override
    public String toString() {
        return "Orders{" +
                "id=" + id +
                ", number='" + number + '\'' +
                ", userId=" + userId +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }
}

8.创建接口OrdersMapper:

package cn.hdc.mapper;

import cn.hdc.pojo.Orders;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface OrdersMapper {
    @Select("select * from tb_orders where user_id = #{uid}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "number",column = "number"),
            @Result(property = "userId",column = "user_id")
    })
    public List<Orders> selectOrdersByUserId(int uid);
}

9.创建接口:UserMapper

package cn.hdc.mapper;

import cn.hdc.pojo.User;
import org.apache.ibatis.annotations.*;

public interface UserMapper {
    @Select("select * from tb_user where id = #{id}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "username",column = "username"),
            @Result(property = "address",column = "address"),
            @Result(property = "ordersList",column = "id",many = @Many(select = "cn.hdc.mapper.OrdersMapper.selectOrdersByUserId"))
    })
    public User selectUserById(int id);
}

10.创建测试类:UserMapperTest:

package cn.hdc.mapper;

import cn.hdc.pojo.User;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class UserMapperTest {
    private SqlSession session;

    private UserMapper userMapper;

    @Before
    public void setUp() throws Exception {
        session = MybatisUtils.getSession();
    }

    @After
    public void tearDown() throws Exception {
        session.commit();
        session.close();
    }

    @Test
    public void selectUserById() {
        userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.selectUserById(1);
        System.out.println(user);
    }
}

11.项目结构:

12.运行结果:

多对多查询

多对多关联使用中间表:

  • 在数据库中,表与表之间的多对多关联关系通常使用一个中间表来维护  

 1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>_20230503</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

2.建库建表:

tb_orders表:

CREATE TABLE `tb_orders` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `number` varchar(32) NOT NULL,
  `user_id` int(32) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `tb_orders_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `tb_user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4

tb_product表:

CREATE TABLE `tb_product` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `price` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4

 tb_ordersitem表:

CREATE TABLE `tb_ordersitem` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `orders_id` int(32) DEFAULT NULL,
  `product_id` int(32) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `orders_id` (`orders_id`),
  KEY `product_id` (`product_id`),
  CONSTRAINT `tb_ordersitem_ibfk_1` FOREIGN KEY (`orders_id`) REFERENCES `tb_orders` (`id`),
  CONSTRAINT `tb_ordersitem_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `tb_product` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4

3.创建实体类:Orders:

package cn.hdc.pojo;

import java.util.List;

public class Orders {
    private int id;
    private String number;
    private int userId;
    private List<Product> productList;

    @Override
    public String toString() {
        return "Orders{" +
                "id=" + id +
                ", number='" + number + '\'' +
                ", userId=" + userId +
                ", productList=" + productList +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public List<Product> getProductList() {
        return productList;
    }

    public void setProductList(List<Product> productList) {
        this.productList = productList;
    }
}

4.创建实体类:Product

package cn.hdc.pojo;

import java.util.List;

public class Product {
    private int id;
    private String name;
    private double price;
    private List<Orders> ordersList;

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", ordersList=" + ordersList +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public List<Orders> getOrdersList() {
        return ordersList;
    }

    public void setOrdersList(List<Orders> ordersList) {
        this.ordersList = ordersList;
    }
}

5.创建接口OrdersMapper

package cn.hdc.mapper;

import cn.hdc.pojo.Orders;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface OrdersMapper {
//    @Select("select * from tb_orders where user_id = #{uid}")
//    @Results({
//            @Result(id = true, property = "id", column = "id"),
//            @Result(property = "number", column = "number"),
//            @Result(property = "userId", column = "user_id")
//    })
//    public List<Orders> selectOrdersByUserId(int uid);

    @Select("select * from tb_orders where id = #{id}")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "number", property = "number"),
            @Result(column = "id", property = "productList", many = @Many(select = "cn.hdc.mapper.ProductMapper.selectProductsByOrdersId"))
    })
    public Orders selectOrderById(int id);
}

6.创建接口:ProductMapper

package cn.hdc.mapper;

import cn.hdc.pojo.Product;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface ProductMapper {
    @Select("select * from tb_product where id in (select product_id from tb_ordersitem where orders_id=#{orderId})")
    public List<Product> selectProductsByOrdersId(int orderId);
}

7.创建工具类MybatisUtils

package cn.hdc.utils;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
import java.io.IOException;
import java.io.Reader;
 
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
 
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
}

8.db.properties

driver.driver=com.mysql.cj.jdbc.Driver
driver.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver.username=root
driver.password=666666

9.mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 环境配置 -->
    <!-- 加载类路径下的属性文件 -->
    <properties resource="db.properties"/>

    <!-- 数据库连接相关配置 ,db.properties文件中的内容-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver.driver}"/>
                <property name="url" value="${driver.url}"/>
                <property name="username" value="${driver.username}"/>
                <property name="password" value="${driver.password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <package name="cn.hdc.mapper"/>
    </mappers>
</configuration>

10.创建测试类OrdersMapperTest

package cn.hdc.mapper;

import cn.hdc.pojo.Orders;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class OrdersMapperTest {
    private SqlSession session;
    private OrdersMapper ordersMapper;

    @Before
    public void setUp() throws Exception {
        session = MybatisUtils.getSession();
    }

    @After
    public void tearDown() throws Exception {
        session.commit();
        session.close();
    }

    @Test
    public void selectOrderById() {
        ordersMapper = session.getMapper(OrdersMapper.class);
        Orders orders = ordersMapper.selectOrderById(1);
        System.out.println(orders);
    }
}

11.项目结构:

12.运行结果:

案例:基于MyBatis注解的学生管理程序

代码示例:

需求:

1.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>_20230503_1</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

2.db.properties

driver.driver=com.mysql.cj.jdbc.Driver
driver.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driver.username=root
driver.password=666666

3.mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 环境配置 -->
    <!-- 加载类路径下的属性文件 -->
    <properties resource="db.properties"/>

    <!-- 数据库连接相关配置 ,db.properties文件中的内容-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver.driver}"/>
                <property name="url" value="${driver.url}"/>
                <property name="username" value="${driver.username}"/>
                <property name="password" value="${driver.password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <package name="cn.hdc.mapper"/>
    </mappers>
</configuration>

4.MyBatisUtils工具类:

package cn.hdc.utils;
 
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 
import java.io.IOException;
import java.io.Reader;
 
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
 
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession();
    }
}

5.建库建表:

s_student表:

CREATE TABLE `s_student` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `cid` int(32) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `cid` (`cid`),
  CONSTRAINT `s_student_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `c_class` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4

c_class表:

CREATE TABLE `c_class` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `classname` varchar(40) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4

6.创建接口StudentMapper:

package cn.hdc.mapper;

import cn.hdc.pojo.Student;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface StudentMapper {
    @Select("select * from s_student where id=#{id}")
    public Student selectStudent(int id);

    @Update("update s_student set name=#{name},age=#{age} where id=#{id}")
    public int updateStudent(Student student);

    @Select("select * from s_student where cid = #{cid}")
    @Results({
            @Result(id = true,column = "id",property = "id"),
            @Result(column = "name",property = "name"),
            @Result(column = "age",property = "age")
    })
    public List<Student> selectStudentsByCid(int cid);
}

7.创建ClassMapper接口:

package cn.hdc.mapper;

import cn.hdc.pojo.IClass;
import org.apache.ibatis.annotations.Many;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface ClassMapper {
    @Select("select * from c_class where id=#{id}")
    @Results({
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "classname", property = "classname"),
            @Result(column = "id",property = "studentList",many = @Many(select = "cn.hdc.mapper.StudentMapper.selectStudentsByCid"))
    })
    public IClass selectClassById(int id);
}

8.创建StudentMapperTest:

package cn.hdc.mapper;

import cn.hdc.pojo.Student;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class StudentMapperTest {
    private SqlSession session;

    @Before
    public void setUp() throws Exception {
        session = MybatisUtils.getSession();
    }

    @After
    public void tearDown() throws Exception {
        session.commit();
        session.close();
    }

    @Test
    public void selectStudent() {
        StudentMapper studentMapper = session.getMapper(StudentMapper.class);
        Student student = studentMapper.selectStudent(2);
        System.out.println(student);
    }

    @Test
    public void updateStudent() {
        StudentMapper studentMapper = session.getMapper(StudentMapper.class);
        Student student = new Student();
        student.setName("Tom");
        student.setAge(23);
        student.setId(4);
        int ret = studentMapper.updateStudent(student);
        if (ret > 0) {
            System.out.println("添加成功!");
        } else {
            System.out.println("添加失败!");
        }
    }
}

9.创建ClassMapperTest测试类:

package cn.hdc.mapper;

import cn.hdc.pojo.IClass;
import cn.hdc.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class ClassMapperTest {
    private SqlSession session;

    @Before
    public void setUp() throws Exception {
        session = MybatisUtils.getSession();
    }

    @After
    public void tearDown() throws Exception {
        session.commit();
        session.close();
    }

    @Test
    public void selectClassById() {
        ClassMapper classMapper = session.getMapper(ClassMapper.class);
        IClass iClass = classMapper.selectClassById(2);
        System.out.println(iClass);
    }
}

10.项目结构:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/486420.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

《Netty》从零开始学netty源码(五十一)之PoolArena的内存释放与扩容

目录 释放空间free()destroyChunk()freeChunk() 扩容reallocate()memoryCopy() 释放空间free() 当chunk使用完毕后需要释放&#xff0c;如果是池化chunk则需要放回池中供下次循环利用&#xff0c;如果是非池化的则直接释放对应的物理空间。 下面继续分析释放具体物理空间的des…

代码随想录算法训练营(总结)|动态规划总结篇

一、动态规划五部曲 确定dp及其下标的含义确定递推关系式初始化值确定遍历顺序验证 二、01背包问题 1. 基本理解 理解&#xff1a;所谓的01背包问题&#xff0c;其关键在于物品只能放入1次&#xff0c;不能够重复利用&#xff0c;因此称呼为01背包问题。与完全背包的区别在…

【深度学习】计算机视觉(十)——Faster RCNN(实践篇)

文章目录 写在最前面 step1&#xff1a;相关说明step2&#xff1a;Prerequisites安装要求tensorflow-gpu1. 安装和测试2. 错误提示① numpy版本② tensorflow版本③TensorRT step3&#xff1a;Installation1. Update your -arch2. Install the Python COCO API3. setup VOC4. D…

【VM服务管家】VM4.2平台SDK_6.4 结果获取类

目录 2.4.1 数据结果&#xff1a;通过流程输出或者模块输出获取数据结果的方法2.4.2 流程回调&#xff1a;某个流程运行开始与结束的回调方法 2.4.1 数据结果&#xff1a;通过流程输出或者模块输出获取数据结果的方法 描述 环境&#xff1a;VM4.2 VS2013及以上 现象&#xff…

从不自量力到 AI 助力,我如何翻译完一整本英文书

披露和声明&#xff1a; 本文提及的翻译作品系使用 AI 技术制作&#xff0c;并经人工调整&#xff0c;具体步骤如文中所述。本文在后期修改过程中使用 ChatGPT 辅助&#xff0c;目的为精简原版中的口语化表述。我的英文水平有限&#xff0c;翻译这本书主要是为了自我学习&…

自动驾驶— Planning - Udacity Self-Driving Car Engineer

第六讲规划 6.1规划简介 在规划中&#xff0c;我们结合了高清地图、定位和预测来构建车辆的轨迹。规划的第一步是路线导航&#xff0c;重点是如何在地图上从A到B。路由以地图数据作为输入&#xff0c;并输出可导航路径。手机上的导航系统就是路线规划的一个例子。在Apollo中&…

高性能——零拷贝

目录 背景 零拷贝定义 传统I/O执行流程 背景 零拷贝算是一个老生常谈的问题啦&#xff0c;很多顶级框架都用到了零拷贝来提升性能&#xff0c;比如我们经常接触到的Kafka 、RocketMQ、Netty 。 零拷贝定义 “拷贝”:就是指数据从一个存储区域转移到另一个存储区域.“零”…

games103——作业2

实验二主要使用隐式积分法以及PBD法完成布料仿真 完整项目已上传至github。 文章目录 基于物理的方法弹簧系统单个弹簧多个弹簧弹簧网络结构化弹簧网络(Structured Spring Networks)非结构化弹簧网络(Unstructured Spring Networks)三角网格表示 代码 求解质量弹簧系统的显示积…

UG NX二次开发(C++)-用UF_OBJ_cycle_objs_in_part遍历对象

文章目录 1、前言2、在UG NX中创建多个体3、创建UF_OBJ_cycle_objs_in_part的使用函数3.1 首先声明函数&#xff1a;3.2定义函数代码3.3 函数调用代码3.4 测试结果 1、前言 UG NX二次开发中&#xff0c;比如体、面、边等&#xff0c;在NXOpen中可以通过Collection来实现&#…

华硕ROG|玩家国度冰刃6双屏GX650RX Windows11原厂预装系统 工厂模式恢复安装带ASUSRecevory一键还原

华硕ROG|玩家国度 冰刃6双屏 GX650RX Windows11原厂预装系统 工厂模式恢复安装带ASUSRecevory一键还原 文件地址&#xff1a;https://pan.baidu.com/s/1snKOsH3OMl3GZLqeAf-GLA?pwd8888 华硕工厂恢复系统 &#xff0c;安装结束后带隐藏分区以及机器所有驱动软件 需准备一个…

【告警通知】Java项目统一异常捕获处理【钉钉告警推送消息】

基础描述 在实际业务中&#xff0c;很多时候都是被动获取系统业务异常&#xff0c;如通过业务部门或者通过客户反馈说某个功能不行时&#xff0c;这样显得系统很被动和呆板在SpringBoot中有统一异常处理可以来实现&#xff0c;当我们检测到非业务异常时&#xff0c;比如空指针…

《SpringBoot中间件设计与实战》第2章 服务治理,超时熔断

需求背景 在流量较大的场景下,举个例子,用户在电商平台下单后开始跳转到在线收银台进行支付。由于支付渠道和网络环境随时都有可能发生问题,那么你该怎么保证支付系统的可靠性呢? 保证支付系统的可靠性需要考虑的点非常多,但这里有一个最直接和重点的内容就支付响应时长…

【王道·计算机网络】第三章 数据链路层【未完】

一、功能 研究思想&#xff1a;水平方向个数据链路层的差距 1.1 数据链路层基本概念 结点&#xff1a;主机、路由器链路&#xff1a;网络中两个节点之间的物理通道&#xff0c;传输介质包含&#xff1a;双绞线、光纤、微波。分为&#xff1a;有线链路、无线链路数据链路&…

TIM输入不捕获-STM32

TIM输入不捕获-STM32 IC(Input Capture) 输入捕获 输入捕获模式下&#xff0c;当通道输入引脚出现指定电平跳变时&#xff0c;当前CNT的值将被锁存到CCR中&#xff0c;可用于测量PWM波形的频率、占空比、脉冲间隔、电平持续时间等参数 每个高级定时器和通用定时器都拥有4个输入…

【Linux】进程学习(2)---理解进程操作

文章目录 查看进程通过系统目录查看通过ps命令查看 通过系统调用获取进程标识符通过系统调用创建进程初识fork函数fork函数的返回值 进程状态阻塞与运行状态Linux内核源码中的进程状态运行状态-R浅度睡眠状态-S深度睡眠状态-D暂停状态-T僵尸状态-Z死亡状态-X 查看进程 通过系统…

操作系统引导(开机过程)

操作系统安装在C盘中&#xff0c;其一步步启动的过程如下&#xff1a; 操作系统要启动&#xff0c;操作系统的数据需要先被放入主存里。 如图所示&#xff0c;计算机的主存由RAM和ROM组成&#xff0c;ROM芯片被集成在电脑主板上&#xff0c;里面存储的是BIOS&#xff08;Basic…

【组合数学算贡献+枚举】CF816div2 C. Monoblock

题解都看了半天才懂 Problem - C - Codeforces 题意&#xff1a; 思路&#xff1a; 一开始的思路是这样的&#xff1a; 只能说&#xff0c;想到了更换枚举对象&#xff0c;然后组合数学算贡献 也想到了修改操作与&#xff08;a[i]和a[i-1]&#xff09;有关 但是我想的是枚…

在Linux上搭建gitlab以及自动化编译部署的完整流程

一、安装gitlab 首先下载gitlab的安装包&#xff0c;地址如下&#xff1a; https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/ubuntu/pool/bionic/main/g/gitlab-ce/ 然后安装下载的包即可&#xff0c;一般还需要安装openssh-server等依赖包&#xff0c;在安装gitlab包之前可以…

【MongoDB】二、MongoDB数据库的基本操作

【MongoDB】二、MongoDB数据库的基本操作 实验目的实验内容任务一&#xff1a;&#xff08;1&#xff09;创建数据库newdb&#xff08;2&#xff09;在数据库newdb中创建集合mycollection&#xff08;3&#xff09;在集合mycollection中插入以下数据&#xff1a;&#xff08;4&…

如何安装 Auto GPT 4:分步指南

动动发财的小手&#xff0c;点个赞吧&#xff01; 您对尝试最新最好的文本生成技术感到兴奋吗&#xff1f; Auto GPT 4 因其令人印象深刻的功能而广为人知&#xff0c;但启动和运行它似乎令人望而生畏。幸运的是&#xff0c;我们在这里[1]提供安装 Auto GPT 4 的分步指南。 1. …