ssm-mybatis mapper补充之注解

ssm-mybatis mapper补充之注解

ssm-mybatis mapper补充之注解

注解说明

使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。
因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句,比如:嵌套联合映射。这里对一些简单的mapper用注解方式实现数据库操作。

准备工作

  1. 工程配置
  2. 工程配置这里就不细说,可以看之前的入门操作说明:
    https://blog.csdn.net/HenryChow_2015/article/details/119649897

  3. 准备数据库表:新建班级、学生、班级学生映射表并写入一些测试数据
  4. CREATE TABLE `class` (
      `id` int NOT NULL AUTO_INCREMENT COMMENT "班级id,主键,自增",
      `name` varchar(255) DEFAULT NULL COMMENT "班级名",
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
    CREATE TABLE `student` (
      `id` int NOT NULL AUTO_INCREMENT COMMENT "主键",
      `name` varchar(10) CHARACTER SET utf8 NOT NULL DEFAULT "123" COMMENT "姓名",
      `sex` varchar(10) CHARACTER SET utf8 DEFAULT NULL COMMENT "性别",
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
    CREATE TABLE `student_class_map` (
      `id` int NOT NULL AUTO_INCREMENT COMMENT "主键,自增",
      `student_id` int NOT NULL COMMENT "学生id",
      `class_id` int NOT NULL COMMENT "班级id",
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;



@Insert

  1. mapper中编写插入接口,插入对象map都行
  2. @Insert("INSERT INTO student (name, sex) VALUES(#{name}, #{sex})")
    void insert(Student student);
  3. 编写测试方法测试
  4. @Test
    public void insert() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student student = new Student();
        student.setName("貂蝉");
        student.setSex("女");
        mapper.insert(student);
        sqlSession.close();
    }
  5. 运行查看结果

@Select

  1. mapper中编写查询接口,返回到map list中
  2. @Select("SELECT s.id as sid,s.`name` as sname,s.sex,c.id as cid,c.`name` as cname FROM student as s " +
            "LEFT JOIN student_class_map as sc ON s.id = sc.student_id " +
            "LEFT JOIN class as c ON sc.class_id = c.id WHERE s.sex = #{sex};")
    List<Map<Object, Object>> getStudentAndClassListBySex(@Param("sex") String s);
  3. 编写测试方法测试
  4. @Test
    public void getStudentAndClassListBySex() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        for (Map map : mapper.getStudentAndClassListBySex("男")) {
            for (Object o : map.keySet()) {
                System.out.print(o + ":" + map.get(o) + " | ");
            }
            System.out.println();
        }
        sqlSession.close();
    }
  5. 运行查看结果

@Delete、@Update: 实现方式类似,不一一举例

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » ssm-mybatis mapper补充之注解