您现在的位置是:首页 >技术教程 >MyBatis之注解开发网站首页技术教程

MyBatis之注解开发

yandao 2024-06-17 11:18:51
简介MyBatis之注解开发

除了XML映射方式,MyBatis还支持注解方式实现POJO对象和数据表之间的关联映射,使用注解的方式一般将SQL语句直接写到接口上。与XML的映射方式相比,基于注解的映射方式相对简单。Mybatis提供的注解有:
在这里插入图片描述

1.环境准备

1.1 数据库准备

USE mybatis;
# 创建一个名称为tb_worker的表
CREATE TABLE  tb_worker( 
     id INT PRIMARY KEY AUTO_INCREMENT,
     name VARCHAR(32),
     age INT,
     sex VARCHAR(8),
     worker_id INT UNIQUE     
);
# 插入2条数据
INSERT INTO tb_worker(name,age,sex,worker_id)VALUES('张三',32,'女',1001);
INSERT INTO tb_worker(name,age,sex,worker_id)VALUES('李四',29,'男',1002);
INSERT INTO tb_worker(name,age,sex,worker_id)VALUES('王五',26,'男',1003);

1.2 Idea基础环境

1.2.1 创建annotaion module

在这里插入图片描述

1.2.2 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">
    <parent>
        <artifactId>mybatis-series</artifactId>
        <groupId>com.biem</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>annotation</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

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

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

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
    </dependencies>
</project>

1.2.3 创建资源

包:4个

(1) src/main/java下创建

com.biem.pojo
com.biem.mapper
com.biem.util

(2) src/test/java下创建

类:4个

(1) com.biem.pojo.Worker.java
package com.biem.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;

/**
 * ClassName: Worker
 * Package: com.biem.pojo
 * Description:
 *
 * @Create 2023/5/19 8:27
 * @Version 1.0
 */
@Data
//@Data : 注在类上,提供类的get、set、equals、hashCode、canEqual、toString方法
@NoArgsConstructor
@AllArgsConstructor
public class Worker {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;
    private Integer workerId;
}
(2) com.biem.mapper.WorkerMapper.java
package com.biem.mapper;

/**
 * ClassName: WorkerMapper
 * Package: com.biem.mapper
 * Description:
 *
 * @Create 2023/5/19 8:27
 * @Version 1.0
 */
public interface WorkerMapper {
}

(3) com.biem.util.MyBatisUtil.java
package com.biem.util;

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.InputStream;

/**
 * ClassName: MybatisUtil
 * Package: com.biem.util
 * Description:
 *
 * @Create 2023/4/5 22:23
 * @Version 1.0
 */
public class MyBatisUtil {
    //利用static(静态)属于类不属于对象,且全局唯一
    private static SqlSessionFactory sqlSessionFactory = null;
    //利用静态块在初始化类时实例化sqlSessionFactory
    static {
        InputStream is= null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);
        }
    }

    /**
     * openSession 创建一个新的SqlSession对象
     * @return SqlSession对象
     */
    public static SqlSession openSession(boolean autoCommit){
        return sqlSessionFactory.openSession(autoCommit);
    }

    public static SqlSession openSession(){
        return sqlSessionFactory.openSession();
    }
    /**
     * 释放一个有效的SqlSession对象
     * @param session 准备释放SqlSession对象
     */
    public static void closeSession(SqlSession session){
        if(session != null){
            session.close();
        }
    }
}


(4) com.biem.test.WorkerTest.java
package com.biem.test;

/**
 * ClassName: WorkerTest
 * Package: com.biem.test
 * Description:
 *
 * @Create 2023/5/19 9:21
 * @Version 1.0
 */
public class WorkerTest {
}

配置:3个

(1) jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
jdbc.username=root
jdbc.password=root
(2) log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) 
"/>
        </layout>
    </appender>
    <logger name="java.sql">
        <level value="debug"/>
    </logger>
    <logger name="org.apache.ibatis">
        <level value="info"/>
    </logger>
    <root>
        <level value="debug"/>
        <appender-ref ref="STDOUT"/>
    </root>
</log4j:configuration>
(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文件-->
    <properties resource="jdbc.properties"></properties>

    <!--将下划线映射为驼峰-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!--设置类型别名-->
    <typeAliases>
        <package name="com.biem.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>

    </environments>

    <!-- 引入映射文件 -->
    <mappers>
        <package name="com.biem.mapper"/>
    </mappers>

</configuration>

2.常用注解

2.1 @Select注解

2.1.1 com.biem.mapper.WorkerMapper.java下添加

    @Select("select * from tb_worker where id=#{id}")
    public Worker findWorkerById(Integer id);

2.1.2 com.biem.test.WorkerTest.java下添加

    @Test
    public void findWorkerById(){
        SqlSession session = MyBatisUtil.openSession();
        WorkerMapper mapper = session.getMapper(WorkerMapper.class);
        System.out.println("mapper.findWorkerById(1) = " + mapper.findWorkerById(1));
        session.close();
    }

2.1.3 输出结果

DEBUG 05-19 10:14:56,714 ==>  Preparing: select * from tb_worker where id=?  (BaseJdbcLogger.java:159) 
DEBUG 05-19 10:14:56,800 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:159) 
DEBUG 05-19 10:14:56,863 <==      Total: 1 (BaseJdbcLogger.java:159) 
mapper.findWorkerById(1) = Worker(id=1, name=张三, age=32, sex=, workerId=1001)

2.2 @Insert注解

2.2.1 com.biem.mapper.WorkerMapper.java下添加

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

2.2.2 com.biem.test.WorkerTest.java下添加

    @Test
    public void inserWorker(){
        SqlSession session = MyBatisUtil.openSession();
        WorkerMapper mapper = session.getMapper(WorkerMapper.class);
        Worker worker = new Worker();
        worker.setName("王强");
        worker.setAge(36);
        worker.setSex("女");
        worker.setWorkerId(1004);
        int result = mapper.insertWorker(worker);
        session.commit();
        session.close();
    }

2.2.3 输出结果

DEBUG 05-19 10:27:51,392 ==>  Preparing: insert into tb_worker(name, age, sex, worker_id) values(?, ?, ?, ?)  (BaseJdbcLogger.java:159) 
DEBUG 05-19 10:27:51,472 ==> Parameters: 王强(String), 36(Integer),(String), 1004(Integer) (BaseJdbcLogger.java:159) 
DEBUG 05-19 10:27:51,477 <==    Updates: 1 (BaseJdbcLogger.java:159) 

2.3 @Update注解

2.3.1 com.biem.mapper.WorkerMapper.java下添加

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

2.3.2 com.biem.test.WorkerTest.java下添加

    @Test
    public void updateWorker(){
        SqlSession session = MyBatisUtil.openSession();
        WorkerMapper mapper = session.getMapper(WorkerMapper.class);
        Worker worker = new Worker();
        worker.setId(4);
        worker.setName("王冰");
        worker.setAge(36);
        int result = mapper.updateWorker(worker);
        if(result>0){
            System.out.println("更新了"+result+"条数据");
        } else {
            System.out.println("更新失败");
        }
        session.commit();
        session.close();
    }

2.3.3 输出结果

DEBUG 05-19 10:40:23,577 ==>  Preparing: update tb_worker set name=?,age=? where id = ?  (BaseJdbcLogger.java:159) 
DEBUG 05-19 10:40:23,640 ==> Parameters: 王冰(String), 36(Integer), 4(Integer) (BaseJdbcLogger.java:159) 
DEBUG 05-19 10:40:23,645 <==    Updates: 1 (BaseJdbcLogger.java:159) 
更新了1条数据

2.4 @Delete注解

2.4.1 com.biem.mapper.WorkerMapper.java下添加

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

2.4.2 com.biem.test.WorkerTest.java下添加

    @Test
    public void deleteWorkerById(){
        SqlSession session = MyBatisUtil.openSession();
        WorkerMapper mapper = session.getMapper(WorkerMapper.class);
        int result = mapper.deleteWorkerById(4);
        if(result>0){
            System.out.println("删除了"+result+"条数据");
        } else {
            System.out.println("删除失败");
        }
        session.close();
    }

2.4.3 输出结果

DEBUG 05-19 10:43:44,179 ==>  Preparing: delete from tb_worker where id=?  (BaseJdbcLogger.java:159) 
DEBUG 05-19 10:43:44,247 ==> Parameters: 4(Integer) (BaseJdbcLogger.java:159) 
DEBUG 05-19 10:43:44,251 <==    Updates: 1 (BaseJdbcLogger.java:159) 
删除了1条数据

2.5 @Param注解

@Param注解的作用是指定SQL语句中的参数,通常用于SQL语句中参数比较多的情况。

2.4.1 com.biem.mapper.WorkerMapper.java下添加

    //mybatis不能识别多个参数,所以多个参数会抛出,
    //Cause: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [arg1, arg0, param1, param2]
    @Select("select * from tb_worker where id=#{id} and name=#{name}")
    public Worker findWorkerByIdAndName1(Integer id, String name);

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

    @Select("select * from tb_worker where id=#{arg1} and name=#{arg0}")
    public Worker findWorkerByIdAndName3(@Param("arg1") Integer id, @Param("arg0") String name);

2.4.2 com.biem.test.WorkerTest.java下添加

    @Test
    public void findWorkerByIdAndName1(){
        SqlSession session = MyBatisUtil.openSession();
        WorkerMapper mapper = session.getMapper(WorkerMapper.class);
        System.out.println("mapper.findWorkerByIdAndName1(1,"张三") = " + mapper.findWorkerByIdAndName1(1, "张三"));
        session.close();
    }

    @Test
    public void findWorkerByIdAndName2(){
        SqlSession session = MyBatisUtil.openSession();
        WorkerMapper mapper = session.getMapper(WorkerMapper.class);
        System.out.println("mapper.findWorkerByIdAndName2(1,"张三") = " + mapper.findWorkerByIdAndName2(1, "张三"));
        session.close();
    }

    @Test
    public void findWorkerByIdAndName3(){
        SqlSession session = MyBatisUtil.openSession();
        WorkerMapper mapper = session.getMapper(WorkerMapper.class);
        System.out.println("mapper.findWorkerByIdAndName3(1,"张三") = " + mapper.findWorkerByIdAndName3(1, "张三"));
        session.close();
    }

2.4.3 输出结果

(1) findWorkerByIdAndName1结果

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [arg1, arg0, param1, param2]
### Cause: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [arg1, arg0, param1, param2]

	at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:77)
	at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:83)
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
	at com.sun.proxy.$Proxy9.findWorkerByIdAndName1(Unknown Source)
	at com.biem.test.WorkerTest.findWorkerByIdAndName1(WorkerTest.java:79)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
	at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [arg1, arg0, param1, param2]
	at org.apache.ibatis.binding.MapperMethod$ParamMap.get(MapperMethod.java:204)
	at org.apache.ibatis.reflection.wrapper.MapWrapper.get(MapWrapper.java:45)
	at org.apache.ibatis.reflection.MetaObject.getValue(MetaObject.java:122)
	at org.apache.ibatis.executor.BaseExecutor.createCacheKey(BaseExecutor.java:219)
	at org.apache.ibatis.executor.CachingExecutor.createCacheKey(CachingExecutor.java:146)
	at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:82)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
	... 30 more

(2) findWorkerByIdAndName2结果

DEBUG 05-19 14:21:20,200 ==>  Preparing: select * from tb_worker where id=? and name=?  (BaseJdbcLogger.java:159) 
DEBUG 05-19 14:21:20,280 ==> Parameters: 1(Integer), 张三(String) (BaseJdbcLogger.java:159) 
DEBUG 05-19 14:21:20,334 <==      Total: 1 (BaseJdbcLogger.java:159) 
mapper.findWorkerByIdAndName2(1,"张三") = Worker(id=1, name=张三, age=32, sex=, workerId=1001)

(3) findWorkerByIdAndName3结果

DEBUG 05-19 14:23:33,639 ==>  Preparing: select * from tb_worker where id=? and name=?  (BaseJdbcLogger.java:159) 
DEBUG 05-19 14:23:33,703 ==> Parameters: 1(Integer), 张三(String) (BaseJdbcLogger.java:159) 
DEBUG 05-19 14:23:33,754 <==      Total: 1 (BaseJdbcLogger.java:159) 
mapper.findWorkerByIdAndName3(1,"张三") = Worker(id=1, name=张三, age=32, sex=, workerId=1001)

3.基于注解的关联查询

MyBatis注解不仅仅可以实现增删改查,MyBatis还提供了一系列注解@Results、@Result、@One、@Many等注解实现关联查询。

3.1 一对一查询

MyBatis使用@One注解实现数据表的一对一查询

3.1.1 环境准备

3.1.1.1 数据库准备

USE mybatis;
# 创建一个名称为tb_idcard的表
CREATE TABLE  tb_idcard( 
     id INT PRIMARY KEY AUTO_INCREMENT,
     CODE VARCHAR(18)
);
# 插入2条数据
INSERT INTO tb_idcard(CODE) VALUES('152221198711020624');
INSERT INTO tb_idcard(CODE) VALUES('152201199008150317');
# 创建一个名称为tb_person的表
CREATE TABLE tb_person( 
     id INT PRIMARY KEY AUTO_INCREMENT,
     name VARCHAR(32),
     age INT,
     sex VARCHAR(8),
     card_id INT UNIQUE,     
     FOREIGN KEY(card_id) REFERENCES tb_idcard(id)
);
# 插入2条数据
INSERT INTO tb_person(name,age,sex,card_id) VALUES('Rose',22,'女',1);
INSERT INTO tb_person(name,age,sex,card_id) VALUES('jack',23,'男',2);

3.1.1.2 实体类准备

3.1.1.2.1 IdCard.java
package com.biem.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * ClassName: IdCard
 * Package: com.biem.pojo
 * Description:
 *
 * @Create 2023/5/19 14:44
 * @Version 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class IdCard {
    private Integer id;                 //主键id
    private String code;                //身份证号码
}

3.1.1.2.2 Person.java
package com.biem.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * ClassName: Person
 * Package: com.biem.pojo
 * Description:
 *
 * @Create 2023/5/19 14:44
 * @Version 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
    private Integer id;          //主键id
    private String name;         //姓名
    private Integer age;         //年龄
    private String sex;          //性别
    private IdCard card;        //人员关联的证件
}

3.1.1.3 接口类准备

3.1.1.3.1 IdCardMapper.java
package com.biem.mapper;

/**
 * ClassName: IdCardMapper
 * Package: com.biem.mapper
 * Description:
 *
 * @Create 2023/5/19 14:48
 * @Version 1.0
 */
public interface IdCardMapper {
}
3.1.1.3.2 PersonMapper.java
package com.biem.mapper;

/**
 * ClassName: PersonMapper
 * Package: com.biem.mapper
 * Description:
 *
 * @Create 2023/5/19 14:49
 * @Version 1.0
 */
public interface PersonMapper {
}

3.1.2 案例测试

根据id查询 Peson对象

3.1.2.1 接口类添加

3.1.2.1.1 IdCardMapper.java

    @Select("select * from tb_idcard where id=#{id}")
    public IdCard findIdCardById(int id);

3.1.2.1.2 PersonMapper.java

    @Select("select * from tb_person where id=#{id}")
    @Results(
            {@Result(column = "card_id",
                     property = "card",
                     one = @One(select = "com.biem.mapper.IdCardMapper.findIdCardById"))})
    Person findPersonById(int id);

3.1.2.2 添加测试类

com.biem.test.PersonTest.java

package com.biem.test;

import com.biem.mapper.PersonMapper;
import com.biem.pojo.Person;
import com.biem.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

/**
 * ClassName: PersonTest
 * Package: com.biem.test
 * Description:
 *
 * @Create 2023/5/19 14:54
 * @Version 1.0
 */
public class PersonTest {

    @Test
    public void findPersonById(){
        SqlSession session = MyBatisUtil.openSession();
        PersonMapper mapper = session.getMapper(PersonMapper.class);
        Person person = mapper.findPersonById(1);
        System.out.println("person = " + person);
        session.close();
    }
}

3.1.2.3 运行结果

DEBUG 05-19 14:57:14,273 ==>  Preparing: select * from tb_person where id=?  (BaseJdbcLogger.java:159) 
DEBUG 05-19 14:57:14,372 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:159) 
DEBUG 05-19 14:57:14,421 ====>  Preparing: select * from tb_idcard where id=?  (BaseJdbcLogger.java:159) 
DEBUG 05-19 14:57:14,421 ====> Parameters: 1(Integer) (BaseJdbcLogger.java:159) 
DEBUG 05-19 14:57:14,440 <====      Total: 1 (BaseJdbcLogger.java:159) 
DEBUG 05-19 14:57:14,443 <==      Total: 1 (BaseJdbcLogger.java:159) 
person = Person(id=1, name=Rose, age=22, sex=, card=IdCard(id=1, code=152221198711020624))

3.2 一对多查询

MyBatis使用@Many注解实现数据表的一对多关联查询,@Many注解的作用等同于XML配登文件中的元素。

3.2.1 环境准备

3.2.1.1 数据库准备

USE mybatis;
# 创建一个名称为tb_user的表
CREATE TABLE tb_user (
  id int(32) PRIMARY KEY AUTO_INCREMENT,
  username varchar(32),
  address varchar(256)
 );
# 插入3条数据
INSERT INTO tb_user VALUES ('1', '小明', '北京');
INSERT INTO tb_user VALUES ('2', '李华', '上海');
INSERT INTO tb_user VALUES ('3', '李刚', '上海');
# 创建一个名称为tb_orders的表
CREATE TABLE tb_orders (
  id int(32) PRIMARY KEY AUTO_INCREMENT,
  number varchar(32) NOT NULL,
  user_id int(32) NOT NULL,
  FOREIGN KEY(user_id) REFERENCES tb_user(id)
);
# 插入3条数据
INSERT INTO tb_orders VALUES ('1', '1000011', '1');
INSERT INTO tb_orders VALUES ('2', '1000012', '1');
INSERT INTO tb_orders VALUES ('3', '1000013', '2');

3.2.1.2 实体类准备

3.2.1.2.2 Orders.java
package com.biem.pojo;

/**
 * ClassName: Orders
 * Package: com.biem.pojo
 * Description:
 *
 * @Create 2023/5/19 15:09
 * @Version 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Orders {
    private Integer id;                //订单id
    private String number;            //订单编号
}

3.2.1.2.2 User.java
import lombok.NoArgsConstructor;

/**
 * ClassName: User
 * Package: com.biem.pojo
 * Description:
 *
 * @Create 2023/5/19 15:05
 * @Version 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;                 // 用户编号
    private String username;           // 用户姓名
    private String address;            // 用户地址
    private List<Orders> ordersList; //用户关联的订单
}

3.2.1.3 接口类准备

3.2.1.3.1 UserMapper.java
package com.biem.mapper;

/**
 * ClassName: UserMapper
 * Package: com.biem.mapper
 * Description:
 *
 * @Create 2023/5/19 15:11
 * @Version 1.0
 */
public interface UserMapper {
}

3.2.1.3.2 OrdersMapper.java
package com.biem.mapper;

/**
 * ClassName: OrdersMapper
 * Package: com.biem.mapper
 * Description:
 *
 * @Create 2023/5/19 15:11
 * @Version 1.0
 */
public interface OrdersMapper {
}

3.2.2 案例测试

3.2.2.1 接口类添加

3.2.2.1.1 OrdersMapper.java

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

3.2.2.1.2 UserMapper.java

    @Select("select * from tb_user where id=#{id} ")
    @Results({@Result(id = true, column = "id", property = "id"),
            @Result(column = "username", property = "username"),
            @Result(column = "address", property = "address"),
            @Result(column = "id", property = "ordersList",
                    many = @Many(select =
                            "com.biem.mapper.OrdersMapper.findOrdersByUserId"))})
    User findUserById(int id);

3.2.2.2 测试类添加

package com.biem.test;

import com.biem.mapper.UserMapper;
import com.biem.pojo.User;
import com.biem.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

/**
 * ClassName: UserTest
 * Package: com.biem.test
 * Description:
 *
 * @Create 2023/5/19 15:16
 * @Version 1.0
 */
public class UserTest {

    @Test
    public void findUserById(){
        SqlSession session = MyBatisUtil.openSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = mapper.findUserById(1);
        System.out.println("user = " + user);
        session.close();
    }
}

3.2.2.3 结果输出

DEBUG 05-19 15:20:50,932 ==>  Preparing: select * from tb_user where id=?  (BaseJdbcLogger.java:159) 
DEBUG 05-19 15:20:51,004 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:159) 
DEBUG 05-19 15:20:51,056 ====>  Preparing: select * from tb_orders where user_id=?  (BaseJdbcLogger.java:159) 
DEBUG 05-19 15:20:51,056 ====> Parameters: 1(Integer) (BaseJdbcLogger.java:159) 
DEBUG 05-19 15:20:51,060 <====      Total: 2 (BaseJdbcLogger.java:159) 
DEBUG 05-19 15:20:51,064 <==      Total: 1 (BaseJdbcLogger.java:159) 
user = User(id=1, username=小明, address=北京, ordersList=[Orders(id=1, number=1000011), Orders(id=2, number=1000012)])

3.3 多对多查询

表与表之间的多对多关联关系通常使用一个中间表来维护,tb_orders和商品表 tb_product为例,这两个表之间的关联关系使用了一个中间表 b_ordersitem 来维护,需要数据库的三个表格

3.3.1 环境准备

3.3.1.1 数据库准备

USE mybatis;

CREATE TABLE tb_orders (
  id int(32) PRIMARY KEY AUTO_INCREMENT,
  number varchar(32) NOT NULL,
  user_id int(32) NOT NULL,
  FOREIGN KEY(user_id) REFERENCES tb_user(id)
);
# 插入3条数据
INSERT INTO tb_orders VALUES ('1', '1000011', '1');
INSERT INTO tb_orders VALUES ('2', '1000012', '1');
INSERT INTO tb_orders VALUES ('3', '1000013', '2');

# 创建一个名称为tb_product的表
CREATE TABLE tb_product (
  id INT(32) PRIMARY KEY AUTO_INCREMENT,
  NAME VARCHAR(32),
  price DOUBLE 
 );
# 插入3条数据
INSERT INTO tb_product VALUES ('1', 'Java基础入门', '44.5');
INSERT INTO tb_product VALUES ('2', 'Java Web程序开发入门', '38.5');
INSERT INTO tb_product VALUES ('3', 'SSM框架整合实战', '50');
# 创建一个名称为tb_ordersitem 的中间表
CREATE TABLE tb_ordersitem (
    id INT(32) PRIMARY KEY AUTO_INCREMENT,
    orders_id INT(32),
    product_id INT(32),
    FOREIGN KEY(orders_id) REFERENCES tb_orders(id),
FOREIGN KEY(product_id) REFERENCES tb_product(id)
);
# 插入3条数据
INSERT INTO tb_ordersitem  VALUES ('1', '1', '1');
INSERT INTO tb_ordersitem  VALUES ('2', '1', '3');
INSERT INTO tb_ordersitem  VALUES ('3', '3', '3');

3.3.1.2 实体类准备

Product.java

package com.biem.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * ClassName: Product
 * Package: com.biem.pojo
 * Description:
 *
 * @Create 2023/5/19 15:26
 * @Version 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
    private Integer id;                //商品id
    private String name;                //商品名称
    private Double price;                //商品单价
    private List<Orders> orders;        //与订单关联的属性
}

Orders.java修改为

package com.biem.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * ClassName: Orders
 * Package: com.biem.pojo
 * Description:
 *
 * @Create 2023/5/19 15:09
 * @Version 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Orders {
    private Integer id;                //订单id
    private String number;            //订单编号
    //关联商品集合属性
    private List<Product> productList;
}

3.3.1.1 接口类准备

3.3.1.1.1 OrdersMapper.java为以下代码,暂时不用修改
package com.biem.mapper;

import com.biem.pojo.Orders;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * ClassName: OrdersMapper
 * Package: com.biem.mapper
 * Description:
 *
 * @Create 2023/5/19 15:11
 * @Version 1.0
 */
public interface OrdersMapper {

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

3.3.1.1.2 ProductMapper.java
package com.biem.mapper;

/**
 * ClassName: ProductMapper
 * Package: com.biem.mapper
 * Description:
 *
 * @Create 2023/5/19 15:28
 * @Version 1.0
 */
public interface ProductMapper {
}

3.3.2 案例测试

3.3.2.1 接口类添加

3.3.2.1.1 ProductMapper.java修改
package com.biem.mapper;

import com.biem.pojo.Product;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * ClassName: ProductMapper
 * Package: com.biem.mapper
 * Description:
 *
 * @Create 2023/5/19 15:28
 * @Version 1.0
 */
public interface ProductMapper {
    @Select("select * from tb_product where id in (select product_id from " +
            "tb_ordersitem where orders_id = #{id} )")
    public List<Product> findProductByOrdersId(int orders_id);
}

3.3.2.1.2 OrdersMapper修改为
package com.biem.mapper;

import com.biem.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;

/**
 * ClassName: OrdersMapper
 * Package: com.biem.mapper
 * Description:
 *
 * @Create 2023/5/19 15:11
 * @Version 1.0
 */
public interface OrdersMapper {

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


    @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 =
                            "com.biem.mapper.ProductMapper.findProductByOrdersId"))})
    public Orders findOrdersById(int id);
}

3.3.2.2 测试类添加

package com.biem.test;

import com.biem.mapper.OrdersMapper;
import com.biem.pojo.Orders;
import com.biem.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

/**
 * ClassName: OrdersTest
 * Package: com.biem.test
 * Description:
 *
 * @Create 2023/5/19 15:32
 * @Version 1.0
 */
public class OrdersTest {
    @Test
    public void findOrdersById(){
        SqlSession session = MyBatisUtil.openSession();
        OrdersMapper mapper = session.getMapper(OrdersMapper.class);
        Orders orders = mapper.findOrdersById(1);
        System.out.println("orders = " + orders);
        session.close();
    }
}

3.3.2.3 结果输出

DEBUG 05-19 15:34:18,076 ==>  Preparing: select * from tb_orders where id=?  (BaseJdbcLogger.java:159) 
DEBUG 05-19 15:34:18,147 ==> Parameters: 1(Integer) (BaseJdbcLogger.java:159) 
DEBUG 05-19 15:34:18,192 ====>  Preparing: select * from tb_product where id in (select product_id from tb_ordersitem where orders_id = ? )  (BaseJdbcLogger.java:159) 
DEBUG 05-19 15:34:18,192 ====> Parameters: 1(Integer) (BaseJdbcLogger.java:159) 
DEBUG 05-19 15:34:18,217 <====      Total: 2 (BaseJdbcLogger.java:159) 
DEBUG 05-19 15:34:18,217 <==      Total: 1 (BaseJdbcLogger.java:159) 
orders = Orders(id=1, number=1000011, productList=[Product(id=1, name=Java基础入门, price=44.5, orders=null), Product(id=3, name=SSM框架整合实战, price=50.0, orders=null)])
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。