MyBatis之注解开发

news2024/12/23 16:21:08

除了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) \n"/>
        </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)])

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

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

相关文章

C语言函数大全-- _w 开头的函数(3)

C语言函数大全 本篇介绍C语言函数大全-- _w 开头的函数 1. _wmkdir 1.1 函数说明 函数声明函数功能int _wmkdir(const wchar_t* dirname);用于创建指定路径名的新目录 参数&#xff1a; dirname &#xff1a; 指向以 null 结尾的宽字符数组&#xff0c;该数组包含要创建的目…

客户管理系统软件怎么用?

阅读本文您将了解&#xff1a;1.客户管理系统的作用&#xff1b;2.客户管理系统软件怎么用&#xff1b;3.客户管理的注意事项。 一、客户管理系统的作用 客户是企业的重要财富&#xff0c;因此客户管理是企业发展过程中至关重要的一部分&#xff0c;那么客户管理怎么做&#…

《编码——隐匿在计算机软硬件背后的语言》精炼——第17章收尾

古之立大事者,不惟有超世之才,亦必有坚忍不拔之志。——苏轼 文章目录 数字计算机硬件软件 数字计算机 数字计算机分为硬件和软件两部分&#xff0c;硬件是组成计算机的设备&#xff0c;软件是输入计算机的指令和数值。之所以将它们区分&#xff0c;是因为相对于硬件而言&…

照片从安卓手机中消失了?让他们恢复回来的几个方法请收好

“我安卓上的所有照片都消失了&#xff0c;我的照片去哪儿了” “我安卓上的所有照片都不见了” “下载的图片从安卓上消失了” …… 您是否遇到类似的问题&#xff1f;导致Android手机照片丢失的原因有很多&#xff0c;例如软件更新、误删、误操作、系统崩溃、应用程序崩溃、…

【算法】——动态规划题目讲解

本期继续为大家带来的是关于动态规划类题目的讲解&#xff0c;对于这类题目大家一定要多加练习&#xff0c;争取掌握。 &#xff08;一&#xff09;不同路径 链接如下&#xff1a;62. 不同路径 题目如下&#xff1a; 算法思路&#xff1a; 1. 状态表⽰&#xff1a; 对于这种「…

【FMC200】基于FMC标准的1路CameraLink Full 输出子卡模块

产品概述 FMC200是一款CameraLink发送FMC子卡模块&#xff0c;该模块支持2路CameraLink Base模式或者1路CameraLink Full模式的图像信号输出。板卡具有2个CameraLink端口&#xff08;SDR26&#xff09;&#xff0c;可以作为模拟相机的输出。 技术指标 图像接口性能&#xff1a…

202305-第二周资讯

山川软件愿为您提供最优质的服务。 您的每一个疑问都会被认真对待&#xff0c;您的每一个建议都将都会仔细思考。 我们希望人人都能分析大数据&#xff0c;人人都能搭建应用。 因此我们将不断完善DEMO、文档、以及视频&#xff0c;期望能在最大程度上快速帮助用户快速解决问…

高效易懂,打造维护性好的Web自动化测试框架PO模式精讲

目录 前言&#xff1a; 一、 PO概述 二、PO何实现于Web框架素自动化测试重中之重。 1.为了保证易维护性和易读性&#xff0c;我们可以在项目中定义一个统一的库&#xff0c;用来存放所有的定位器类。 2.定义一个基础的类&#xff0c;该类用于针对PO的元素定位进行封装。 3…

Visual Studio 2022 17.7 发布首个预览版

Visual Studio 2022 17.7 已发布首个预览版&#xff0c;这个版本有大量社区贡献的新改进&#xff0c;主要改动如下&#xff1a; 生产效率 文件对比功能&#xff0c;可以在 Solution Explorer 中对比不同的文件差异。在资源管理器中右键单击一个文件&#xff0c;然后使用上下文…

Java 中 Token 是什么,有哪些用途

简介 Token 是一种身份验证机制&#xff0c;通常由服务器生成并返回给客户端&#xff0c;客户端在后续的请求中携带 Token&#xff0c;以证明自己的身份。在 Java 中&#xff0c;Token 的应用场景非常广泛&#xff0c;例如用户登录、API 认证、OAuth 授权等等。 在用户登录的…

Hash索引和B+树

Hash索引和B树所有有什么区别或者说优劣呢? 首先要知道Hash索引和B树索引的底层实现原理&#xff1a; hash索引底层就是hash表&#xff0c;进行查找时&#xff0c;调用一次hash函数就可以获取到相应的键值&#xff0c;之后进行回表查询获得实际数据。B树底层实现是多路平衡查…

晨控CK-GW208-EC与欧姆龙PLC工业EtherCAT协议通讯指南

晨控CK-GW208-EC与欧姆龙PLC工业EtherCAT协议通讯指南 EtherCAT 是一种实时以太网络通讯协议&#xff0c;旨在解决传统现场总线系统在数据传输速率和复杂性方面的限制。相比传统现场总线&#xff0c;EtherCAT 的数据传输速率有了极大的提升&#xff0c;同时&#xff0c;EtherC…

借《2023年Q1TikTok电商带货达人趋势分析报告》教你分析TikTok数据报告

现今TikTok的电商业务正进入爆发期。在众多跨境电商的商业营销中&#xff0c;许多商家把TikTok作为重点选择的平台&#xff0c;期望能搭上这波海外流量红利的巨轮。TikTok营销正越来越受商家青睐和使用。那么作为TikTok电商商家&#xff0c;该如何挑选高匹配、高ROI的带货达人&…

公司招了一个00后,以为是个小年轻,没想到人家是个卷王...

公司前段缺人&#xff0c;也面了不少测试&#xff0c;结果竟然没有一个合适的。一开始瞄准的就是中级的水准&#xff0c;也没指望来大牛&#xff0c;提供的薪资也不低&#xff0c;面试的人很多&#xff0c;但平均水平很让人失望。 令我印象最深的是一个00后测试员&#xff0c;…

基于αβ剪枝算法的五子棋

访问【WRITE-BUG数字空间】_[内附完整源码和文档] 五子棋是世界智力运动会竞技项目之一&#xff0c;是一种两人对弈的纯策略型棋类游戏&#xff0c;是世界智力运动会竞技项目之一&#xff0c;通常双方分别使用黑白两色的棋子&#xff0c;下在棋盘直线与横线的交叉点上&#xf…

Husky + lint-staged + ESlint + Prettier(可选) 实现git增量代码lint校验

工具介绍 Husky lint-staged ESlint Prettier(可选) 实现git增量代码lint校验 Husky&#xff1a;一个为 git 客户端增加 hook 的工具&#xff0c;它有一些钩子函数&#xff0c;比如pre-commit、 pre-push等lint-staged: 一个过滤出 git 代码暂存区文件的工具&#xff0c;在…

防火墙NAT策略中各项之间以及策略与策略之间的关系

实验结论 将实验结论写在前面方便大家直接查看 1、NAT策略中rule与rule之间的关系为“或”的关系&#xff0c;即多个rule存在时&#xff0c;流量只需要匹配其中一个rule即可&#xff0c;流量会按照匹配的rule规则进行流量转发。&#xff08;华为华三的防火墙rule是没有ID的&a…

都说今年软件测试炸了,到底炸到什么程度呢?

软件测试薪资“乱”了 随着互联网行业的发展&#xff0c;每年都有有数以万计的求职者推开软件测试的大门&#xff0c;软件测试从业人员数逐年递增&#xff0c;市场对于软件测试人员的要求也越来越高&#xff0c;所以很多的初级测试人员找不到工作&#xff0c;导致了都在说软件…

十年软件测试工程师感悟,写给想要转行的软件测试新人

作为一个30岁并且奋战在测试一线的测试员&#xff0c;被人无数次问到这个问题&#xff0c;也回答过无数次。 刚看到知乎上的一个问题&#xff1a;程序员真的干到35岁就干不动了吗&#xff1f;想到在测试行业真的干到35就干不动了吗&#xff1f;软件测试能做到多少岁?也有很多…

idea插件完成junit代码生成,和springboot代码示例

在idea环境下&#xff0c;可以用过插件的方式自动生成juint模板代码。不过具体要需要自己手动编写。 1、安装插件 打开idea&#xff0c;file–settings–plugins&#xff0c;搜索和安装插件&#xff08;JunitGenerator V2.0和JUnit&#xff09;&#xff0c;安装后&#xff0c;后…