Mybatis的注解开发学习笔记

news2024/11/13 9:36:30

学习视频:5001 @Select注解_哔哩哔哩_bilibili~5009 案例:基于MyBatis注解的学生管理程序_哔哩哔哩_bilibili

目录

1.基于注解的单表增删改查

        1.1@Select注解

1.2Insert注解

1.3Update注解

1.4Delete注解

1.5Param注解

2.基于注解的关联查询

        2.1一对一查询

2.2一对多查询

2.3多对多查询

3.基于MyBatis注解的学生管理程序

查询id为2的学生信息 

修改学生信息

一对多查询班级为二班的学生


1.基于注解的单表增删改查

        1.1@Select注解

数据准备

product表

package com.it.pojo;

public class Product    {
    private int id;
    private String goodsname;
    private int price;
    private int typeid;

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

    public int getId() {
        return id;
    }

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

    public String getGoodsname() {
        return goodsname;
    }

    public void setGoodsname(String goodsname) {
        this.goodsname = goodsname;
    }

    public int getPrice() {
        return price;
    }

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

    public int getTypeid() {
        return typeid;
    }

    public void setTypeid(int typeid) {
        this.typeid = typeid;
    }
}
package com.it.dao;

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

public interface ProductMapper {
    @Select("select  * from product where id=#{id}")
    public Product findProductById(int id);

}

package com.it.dao;

import com.it.pojo.Product;
import com.it.utils.MyBatisUtils;
import junit.framework.TestCase;
import org.junit.Before;

import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Test;

public class ProductMapperTest extends TestCase {
    private ProductMapper productMapper;
    private SqlSession session;

    @Before
    public void setUp()
    {
        session= MyBatisUtils.getSession();
       productMapper=session.getMapper(ProductMapper.class);
    }
    @Test
    public void testFindProductById() {
      Product product= productMapper.findProductById(1);
        System.out.println(product);

    }

    @After
    public void release()
    {
        session.close();
    }


}


1.2Insert注解


    @Insert("insert into product(goodsname,price,typeid) values (#{goodsname},#{price},#{typeid})")
    public int insertProduct(Product product);
 @Test
    public void testinsertProduct()
    {
        Product product2=new Product();
        product2.setGoodsname("风扇");
        product2.setPrice(200);
        product2.setTypeid(2);
        int  i= productMapper.insertProduct(product2);
        System.out.println(i);
        session.commit();

    }


1.3Update注解

   @Update("update product set goodsname=#{goodsname},price=#{price} where id=#{id}")
    public int updateProduct(Product product);
 @Test
    public void  testupdateProduct()
    {
        Product product2=new Product();
        product2.setGoodsname("大风扇");
        product2.setId(5);
        product2.setPrice(300);
        int i=    productMapper.updateProduct(product2);
        System.out.println(i);
        session.commit();


    }


1.4Delete注解

 @Delete("delete from product where id=#{id}")
    public int deleteProduct(int id);
  @Test
    public void testdeleteProduct()
    {
        int i= productMapper.deleteProduct(5);
        if (i>0)
        {
            System.out.println("删除成功");
        }
        session.commit();


    }


1.5Param注解

@Select("select * from product where id=#{param01} and goodsname=#{param02}")
    public Product selectProductByIdAndGoodsname(@Param("param01") int id,
                                            @Param("param02") String goodsname);
 @Test
    public void testselectProductByIdAndGoodsname()
    {
        Product product=productMapper.selectProductByIdAndGoodsname(1,"电视机");
        System.out.println(product);

    }


2.基于注解的关联查询

        2.1一对一查询

package com.it.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;
    }
}
package com.it.pojo;

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

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

    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 getCard() {
        return card;
    }

    public void setCard(IdCard card) {
        this.card = card;
    }
}
package com.it.dao;

import com.it.pojo.IdCard;
import org.apache.ibatis.annotations.Select;

public interface IdCardMapper {

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

}

public interface PersonMapper {

    @Select("select * from tb_person where id=#{id}")
    @Results({@Result(
                    column = "card_id",
                    property = "card",
                    one=@One(select = "com.it.dao.IdCardMapper.selectIdCardById")
    )})
    Person selectPersonById(int id);

}
public class PersonMapperTest extends TestCase  {

    private PersonMapper personMapper;
    private SqlSession session;

    @Before
    public void setUp()
    {
        session= MyBatisUtils.getSession();
        personMapper=session.getMapper(PersonMapper.class);
    }
    @Test
    public void testSelectPersonById() {
       Person person=personMapper.selectPersonById(1);


        System.out.println(person.toString());


    }

    @After
    public void release()
    {
        session.close();
    }
}

这里将mybatis版本改为了3.5.3,不然报错 


2.2一对多查询


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;
    }
}
public class Users {
    private int id;
    private String username;
    private String address;
    private List<Orders> ordersList;

    @Override
    public String toString() {
        return "Users{" +
                "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 interface OrdersMapper {



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


}
public interface UsersMapper {


    @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 = "com.it.dao.OrdersMapper.selectOrdersByUserId")
            )

    })
    public Users selectUserById(int id);

}
public class UsersMapperTest {

    @Test
    public void testSelectUserById() {
        SqlSession session= MyBatisUtils.getSession();
        UsersMapper usersMapper = session.getMapper(UsersMapper.class);
    Users users= usersMapper.selectUserById(1);
        System.out.println(users);
        session.close();


    }
}


2.3多对多查询

public class Orders {
    private int id;
    private String number;
    private int userId;
    private List<Product2>product2List;

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

    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;
    }
}
import java.util.List;

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

    @Override
    public String toString() {
        return "Product2{" +
                "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;
    }
}
public interface Product2Mapper {


    @Select("select * from tb_product where id in"+"(select product_id from tb_ordersitem where orders_id=#{orderId})")
    public List<Product2> selectProduct2sByOrdersId(int orderId);

}
    @Select("select  * from tb_orders where id=#{id}")
    @Results(
            {
             @Result(id = true,column = "id",property = "id"),
             @Result(column = "number",property = "number"),
             @Result(
                     property = "product2List",
                     column = "id",
                     many = @Many(select = "com.it.dao.Product2Mapper.selectProduct2sByOrdersId")
             )
            }
    )
    public Orders selectOrdersById(int id);
public class OrdersMapperTest extends TestCase {

    public void testSelectOrdersById() {
        SqlSession session= MyBatisUtils.getSession();
        OrdersMapper ordersMapper = session.getMapper(OrdersMapper.class);

        Orders orders = ordersMapper.selectOrdersById(1);

        System.out.println(orders);
        session.close();

    }
}


3.基于MyBatis注解的学生管理程序

数据准备

CREATE TABLE student(
	id INT PRIMARY KEY AUTO_INCREMENT,
	NAME VARCHAR(20),
	age INT,
	cid INT
);
INSERT INTO student VALUES(1,'张三',18,1);
INSERT INTO student VALUES(2,'李四',18,2);
INSERT INTO student VALUES(3,'王五',19,2);
INSERT INTO student VALUES(4,'赵六',20,1);

CREATE TABLE class(
	id INT PRIMARY KEY AUTO_INCREMENT,
	classname VARCHAR(20)
);
INSERT INTO class VALUES(1,'一班');
INSERT INTO class VALUES(2,'二班');




public class Student {
    private int id;
    private  String name;
    private  int age;
    private  int cid;

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

    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 int getCid() {
        return cid;
    }

    public void setCid(int cid) {
        this.cid = cid;
    }
}
public class Iclass {
    private int id;
    private String classname;
    //一对多映射
    private List<Student>studentList;

    @Override
    public String toString() {
        return "Iclass{" +
                "id=" + id +
                ", classname='" + classname + '\'' +
                ", studentList=" + studentList +
                '}';
    }

    public String getClassname() {
        return classname;
    }

    public void setClassname(String classname) {
        this.classname = classname;
    }

    public int getId() {
        return id;
    }

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

    public List<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
        this.studentList = studentList;
    }
}

查询id为2的学生信息 

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


}
public class StudentMapperTest extends TestCase {

    public void testSelectStudentById() {
        SqlSession session= MyBatisUtils.getSession();

        StudentMapper studentMapper= session.getMapper(StudentMapper.class);

        Student student= studentMapper.selectStudentById(2);
        System.out.println(student);
        session.close();


    }
}


修改学生信息

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

        SqlSession session= MyBatisUtils.getSession();
        StudentMapper studentMapper= session.getMapper(StudentMapper.class);
        Student student= new Student();
        student.setName("小吴");
        student.setAge(20);
        student.setId(4);
        int i= studentMapper.updateStudent(student);
        if(i>0){
            System.out.println("修改成功");
        }
        session.commit();
        session.close();


    }


一对多查询班级为二班的学生

   @Select("select * from 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);
    @Select("select  * from class where id=#{id}")
    @Results({
            @Result(id = true,column = "id",property = "id"),
            @Result(property = "classname",column = "classname"),
            @Result(property = "studentList",
                    column = "id",
                    many =@Many(select = "com.it.dao.StudentMapper.selectStudentsByCid")
            )
    })
    public Iclass selectClassById(int id);

public class ClassMapperTest extends TestCase {

    public void testSelectClassById() {
        SqlSession session= MyBatisUtils.getSession();
        ClassMapper classMapper = session.getMapper(ClassMapper.class);
        Iclass iclass =classMapper.selectClassById(2);
        System.out.println(iclass);

        session.close();
    }
}

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

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

相关文章

[Meachines] [Easy] nibbles Nibbleblog-Upload

信息收集 IP AddressOpening Ports10.10.10.75TCP:22,80 $ nmap -p- 10.10.10.75 --min-rate 1000 -sC -sV PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0) | ssh-hostkey: | 2048 c4:f8:ad:e8:f8:04:…

实践致知第17享:电脑忽然黑屏的常见原因及处理方法

一、背景需求 小姑电话说&#xff1a;最近&#xff0c;电脑忽然就黑屏了&#xff08;如下图所示&#xff09;&#xff0c;但是等待几十秒甚至一分钟&#xff0c;电脑就能自然恢复了&#xff0c;这种状况一天能出现三四次&#xff0c;怎么办&#xff1f; 二、分析诊断 电脑黑屏…

C++从入门到起飞之——string类用法 全方位剖析!

&#x1f308;个人主页&#xff1a;秋风起&#xff0c;再归来~&#x1f525;系列专栏&#xff1a;C从入门到起飞 &#x1f516;克心守己&#xff0c;律己则安 目录 1. 为什么学习string类&#xff1f; 1.1 C语言中的字符串 1.2 两个面试题(先不做讲解) 2. 标准库中…

IMYAI智能助手介绍:全能AI工具箱,AI爱好者AIGC系统的首选。

IMYAI系统官方网站&#xff1a;https://new.imyai.top 引言&#xff1a; IMYAI系统是一款集多种先进AI技术于一身的创作工具箱&#xff0c;为用户提供无限的创作可能。不论您是想创作精彩的文章&#xff0c;还是创作精美的绘画作品&#xff0c;IMYAI系统都能满足您的需求。它集…

不想要反馈的错误遮挡页面,,想让它在控制台提示

开始页面是这样的 然后在vue.config.js 中修改 devServer: {client: {//当出现编译错误或警告时&#xff0c;在浏览器中是否显示全屏覆盖。 示例为只显示错误信息overlay: {runtimeErrors: false,},},},然后关闭服务&#xff0c;重新运行项目。 结果

【Netty】netty启动流程源码解析

文章目录 Netty整体架构一个启动流程源码解析new NioEventLoopGroup(1)构建线程池基础信息构建线程选择策略 groupchannelhandlerchildHandlerbindinitAndRegister反射创建 NioServerSocketChannel 对象init 注册channeldoBind0 流程图思考 Netty整体架构 是什么&#xff1a; N…

【学习方法】高效学习因素 ① ( 开始学习 | 高效学习因素五大因素 | 高效学习公式 - 学习效果 = 时间 x 注意力 x 精力 x 目标 x 策略 )

文章目录 一、高效学习因素1、开始学习2、高效学习因素五大因素3、高效学习公式 - 学习效果 时间 x 注意力 x 精力 x 目标 x 策略 一、高效学习因素 1、开始学习 对于 学习差 , 调皮捣蛋 的学生 , 不要把 学习成绩差 的 原因 归因为 不爱学习 / 没有学习方法 , 可能是 还没有 …

Docker-学习笔记(借助宝塔面板)

ubuntu环境 一、安装 可以参考官网进行或其他博客进行安装 1.进入宝塔面板 进图Docker菜单&#xff0c;查看是否提示安装。 2.查看是否安装 查看版本 docker -v 证明已经安装 二、常用命令 1.查看版本 docker -v 2.启动、停止、重启docker systemctl start docker…

windows C++-通过 C++/WinRT 使用 API(一)

本文介绍如何使用 C/WinRT API&#xff0c;无论它们是 Windows 的一部分、由第三方组件供应商或自行实现。 本文中的代码示例较短&#xff0c;并且很容易试验&#xff0c;可以通过创建新的 Windows 控制台应用程序 (C/WinRT) 项目和复制粘贴代码来重现它们。 但是&#xff0c;…

【Redis】浅谈架构和认识Redis

目录 架构演进 单机架构 应用数据分离架构 应用服务集群架构 读写分离/主从分离架构 冷热分离架构&#xff08;引入缓存&#xff09; 垂直分库 微服务架构 认识Redis Redis的特性 架构演进 单机架构 简单来说就是只有一台服务器&#xff0c;这个服务器用来负责所有…

GlobalMapper方量计算(两期地形对比,提取填挖方区域及每个区域的方量)

0.序 在工程设计中&#xff0c;经常需要根据设计方案和现状地形之间进行方量计算&#xff0c;尤其关注方量变化的区域&#xff0c;哪些区域需要填方&#xff0c;哪些区域需要挖方&#xff0c;并依据此进行方量的平衡。 在流域管理中&#xff0c;尤其是湿地、三角洲等容易淤积或…

详细分析Java中的SPI机制(附Demo)

目录 前言1. 基本知识2. Demo3. 解读源码 前言 相关的Java知识推荐阅读&#xff1a; java框架 零基础从入门到精通的学习路线 附开源项目面经等&#xff08;超全&#xff09;【Java项目】实战CRUD的功能整理&#xff08;持续更新&#xff09; 1. 基本知识 SPI&#xff08;S…

PANDA:免微调提升大型语言模型领域特定能力的新方法

人工智能咨询培训老师叶梓 转载标明出处 大模型虽然在广泛的任务上具有通用性&#xff0c;但在面对特定领域的任务时&#xff0c;它们的性能往往不如专门为这些领域训练的模型。传统的知识蒸馏&#xff08;Knowledge Distillation, KD&#xff09;方法通过资源密集型的微调过程…

怎么在电脑上查找打印机打印过的文件?告别翻箱倒柜!电脑查找已打印文件技巧公示!

在日常办公中&#xff0c;我们经常会使用打印机来输出各种文件&#xff0c;但有时候&#xff0c;我们可能需要回顾或查找之前打印过的文件。然而&#xff0c;这些文件一旦打印完成&#xff0c;往往就离开了我们的电脑屏幕&#xff0c;进入了纸质世界&#xff0c;而电子文件可能…

Tree-of-Traversals:结合知识图谱与大模型,通过树遍历和回溯寻找高置信度推理路径

Tree-of-Traversals&#xff1a;结合知识图谱与大模型&#xff0c;通过树遍历和回溯寻找高置信度推理路径 Tree-of-Traversals算法解析对比 MindMap1. 与知识图谱&#xff08;KGs&#xff09;的整合2. 推理方法3. 灵活性与可扩展性4. 在医学诊断中的应用 速度和准确1. 速度2. 推…

数据结构第九讲:二叉树

数据结构第九讲&#xff1a;二叉树 1.实现链式结构二叉树1.1二叉树的节点结构1.2创建二叉树节点1.3前中后序遍历1.3.1前序遍历1.3.2中序遍历1.3.3后序遍历1.3.4总结 1.4二叉树结点的个数1.4.1错误示范1.4.2实现方法 1.5二叉树叶子结点的个数1.6二叉树第k层结点的个数1.7二叉树的…

看门狗应用编程-I.MX6U嵌入式Linux C应用编程学习笔记基于正点原子阿尔法开发板

看门狗应用编程 看门狗应用编程介绍 看门狗定时器的基本概念 看门狗是一个可以在一定时间内被复位/重置的计数器 如果在规定时间内没有复位&#xff0c;看门狗计时器溢出会对CPU产生复位信号使系统重启 有些看门狗可以只产生中断信号而不会使系统复位 I.MX6UL/I.MX6ULL So…

如何减少内存碎片的产生——页

文章目录 1 页的设计目的2 进程块和主存块的对应关系3 页、页框、页表3.1 页&#xff08;Page&#xff09;3.2 页框&#xff08;Page Frame&#xff09;3.3 页表&#xff08;Page Table&#xff09; 4 逻辑地址到物理地址的转换4.1 转换过程4.2 具体示例4.3 图示 参考资料封面 …

C语言程序设计25

《C程序设计教程&#xff08;第四版&#xff09;——谭浩强》 习题2.2 分析下面程序的运行结果&#xff0c;然后上机验证。 代码&#xff1a; //《C程序设计教程&#xff08;第四版&#xff09;——谭浩强》 //习题2.2 分析下面程序的运行结果&#xff0c;然后上机验证。#inc…

【C语言篇】操作符详解(下篇)

文章目录 操作符详解&#xff08;下篇&#xff09;前言条件操作符移位操作符左移操作符右移操作符 位操作符下标引用操作符函数调用操作符 操作符的属性&#xff1a;优先级和结合性优先级结合性表达式求值整形提升算术转换 操作符详解&#xff08;下篇&#xff09; 前言 操作…