mybatis入門-3 基於註解的curd 和註解一對一一對多查詢

環境sqlsql

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for course
-- ----------------------------
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course`  (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '課程ID',
  `title` varchar(1024) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '課程標題',
  `subtitle` varchar(1024) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '課程副標題',
  `status` enum('draft','published','closed') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'draft' COMMENT '課程狀態',
  `type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'normal' COMMENT '課程類型',
  `maxStudentNum` int(11) NOT NULL DEFAULT 0 COMMENT '直播課程最大學員數上線',
  `showStudentNumType` enum('opened','closed') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'opened' COMMENT '學員數顯示模式',
  `serializeMode` enum('none','serialize','finished') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'none' COMMENT '連載模式',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 749 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of course
-- ----------------------------
INSERT INTO `course` VALUES (9, 'test', '', 'published', 'normal', 0, 'opened', 'none');
INSERT INTO `course` VALUES (11, '人員管理培訓', '', 'published', 'normal', 0, 'opened', 'none');
INSERT INTO `course` VALUES (14, '行政培訓', '', 'published', 'normal', 0, 'opened', 'none');

SET FOREIGN_KEY_CHECKS = 1;
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for course_lesson
-- ----------------------------
DROP TABLE IF EXISTS `course_lesson`;
CREATE TABLE `course_lesson`  (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '課時ID',
  `courseId` int(10) UNSIGNED NOT NULL COMMENT '課時所屬課程ID',
  `chapterId` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '課時所屬章節ID',
  `number` int(10) UNSIGNED NOT NULL COMMENT '課時編號',
  `seq` int(10) UNSIGNED NOT NULL COMMENT '課時在課程中的序號',
  `status` enum('unpublished','published') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'published' COMMENT '課時狀態',
  `title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '課時標題',
  `summary` text CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT '課時摘要',
  `tags` text CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT '課時標籤',
  `type` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'text' COMMENT '課時類型',
  `content` text CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT '課時正文',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9433 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of course_lesson
-- ----------------------------
INSERT INTO `course_lesson` VALUES (24, 9, 23, 1, 3, 'published', '視頻一', '', NULL, 'video', '');
INSERT INTO `course_lesson` VALUES (161, 14, 109, 1, 2, 'published', '五險一金', '', NULL, 'video', '');
INSERT INTO `course_lesson` VALUES (317, 9, 26, 4, 9, 'published', 'testpdf', '', NULL, 'document', '');
INSERT INTO `course_lesson` VALUES (330, 9, 26, 5, 10, 'published', 'testcname', NULL, NULL, 'testpaper', NULL);
INSERT INTO `course_lesson` VALUES (359, 9, 26, 6, 11, 'published', '測試漏題', NULL, NULL, 'testpaper', NULL);
INSERT INTO `course_lesson` VALUES (367, 9, 26, 7, 12, 'published', 'test1', NULL, NULL, 'testpaper', NULL);
INSERT INTO `course_lesson` VALUES (369, 9, 26, 8, 13, 'published', 'test3', NULL, NULL, 'testpaper', NULL);
INSERT INTO `course_lesson` VALUES (566, 9, 23, 2, 4, 'published', 'aaaaaa', '', NULL, 'video', '');INSERT INTO `course_lesson` VALUES (903, 14, 426, 7, 10, 'published', '郵箱設置', '如何設置公司郵箱', NULL, 'video', '');
INSERT INTO `course_lesson` VALUES (918, 14, 432, 20, 25, 'published', 'CRC學習資料', 'CRC學習資料、行政學習資料講解', NULL, 'video', '');
INSERT INTO `course_lesson` VALUES (921, 14, 432, 24, 29, 'published', '工做日誌', '', NULL, 'video', '');;
INSERT INTO `course_lesson` VALUES (3237, 14, 426, 8, 11, 'published', '釘釘', '', NULL, 'video', '');
INSERT INTO `course_lesson` VALUES (3357, 11, 279, 26, 34, 'published', 'How To Use KPI', '1. Purpose of KPI\r\n2. KPI Execution\r\n3. Case Study', NULL, 'video', '');
INSERT INTO `course_lesson` VALUES (3919, 11, 1347, 42, 58, 'published', '成長之路---「PM和LM合做篇」', '', NULL, 'video', '');
INSERT INTO `course_lesson` VALUES (3995, 11, 1071, 47, 65, 'published', '8月人員管理會議', 'People management meeting of Aug.', NULL, 'video', '');INSERT INTO `course_lesson` VALUES (5376, 11, 231, 4, 6, 'published', '人員管理項目安排技巧', '', NULL, 'video', '');
INSERT INTO `course_lesson` VALUES (5419, 14, 429, 19, 23, 'published', '第五版員工手冊修改內容詳細講解', '', NULL, 'video', '');SET FOREIGN_KEY_CHECKS = 1;
DROP TABLE IF EXISTS `course_chapter`;
CREATE TABLE `course_chapter`  (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '課程章節ID',
  `courseId` int(10) UNSIGNED NOT NULL COMMENT '章節所屬課程ID',
  `type` enum('chapter','unit') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT 'chapter' COMMENT '章節類型:chapter爲章節,unit爲單元。',
  `parentId` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'parentId大於0時爲單元',
  `number` int(10) UNSIGNED NOT NULL COMMENT '章節編號',
  `seq` int(10) UNSIGNED NOT NULL COMMENT '章節序號',
  `title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '章節名稱',
  `createdTime` int(10) UNSIGNED NOT NULL COMMENT '章節建立時間',
  `copyId` int(10) NOT NULL DEFAULT 0 COMMENT '複製章節的id',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1894 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of course_chapter
-- ----------------------------
INSERT INTO `course_chapter` VALUES (22, 9, 'chapter', 0, 1, 1, '視頻', 1490679375, 0);
INSERT INTO `course_chapter` VALUES (23, 9, 'unit', 22, 1, 2, '第一課', 1490679388, 0);
INSERT INTO `course_chapter` VALUES (24, 9, 'unit', 22, 2, 5, '第二課', 1490679398, 0);
INSERT INTO `course_chapter` VALUES (25, 9, 'unit', 22, 3, 7, '第三課', 1490679405, 0);
INSERT INTO `course_chapter` VALUES (26, 9, 'chapter', 0, 2, 8, '考試', 1490679412, 0);
INSERT INTO `course_chapter` VALUES (109, 14, 'chapter', 0, 1, 1, '五險一金培訓', 1491905133, 0);
INSERT INTO `course_chapter` VALUES (228, 11, 'chapter', 0, 1, 1, '各人員管理崗位的工做職責和考覈標準', 1492401052, 0);
INSERT INTO `course_chapter` VALUES (231, 11, 'chapter', 0, 2, 3, '人員管理工做流程指導', 1492401110, 0);
INSERT INTO `course_chapter` VALUES (261, 11, 'chapter', 0, 6, 27, '溝通相關知識&案例分享', 1492401289, 0);
INSERT INTO `course_chapter` VALUES (273, 11, 'chapter', 0, 7, 32, '員工情緒的管理和疏導', 1492401337, 0);
INSERT INTO `course_chapter` VALUES (276, 11, 'chapter', 0, 5, 18, '團隊管理', 1492401346, 0);
INSERT INTO `course_chapter` VALUES (279, 11, 'chapter', 0, 8, 33, 'KPI的溝通和評分', 1492401354, 0);
INSERT INTO `course_chapter` VALUES (282, 11, 'chapter', 0, 9, 36, '離職緣由分析和離職人員管理', 1492401362, 0);
INSERT INTO `course_chapter` VALUES (405, 11, 'chapter', 0, 17, 60, 'co-v相關培訓', 1495607913, 0);
INSERT INTO `course_chapter` VALUES (423, 14, 'chapter', 0, 2, 3, 'SMO新員工入職流程', 1497426318, 0);
INSERT INTO `course_chapter` VALUES (426, 14, 'unit', 423, 1, 4, '入職第一天準備事宜', 1497426412, 0);
INSERT INTO `course_chapter` VALUES (429, 14, 'unit', 423, 2, 13, '入職第一週學習事宜', 1497426433, 0);
INSERT INTO `course_chapter` VALUES (432, 14, 'unit', 423, 3, 24, '試用期學習事宜', 1497426454, 0);
INSERT INTO `course_chapter` VALUES (594, 11, 'chapter', 0, 10, 40, '投訴處理流程培訓', 1505384579, 0);
INSERT INTO `course_chapter` VALUES (693, 14, 'chapter', 0, 3, 35, '關於考勤打卡、timesheet、工做量審覈表的培訓', 1514371064, 0);
INSERT INTO `course_chapter` VALUES (696, 14, 'unit', 693, 1, 36, '關於考勤打卡、timesheet、工做量審覈表的培訓', 1514371256, 0);
INSERT INTO `course_chapter` VALUES (916, 11, 'chapter', 0, 11, 42, 'CAPA&Issue Escalation', 1529054797, 0);
INSERT INTO `course_chapter` VALUES (923, 11, 'chapter', 0, 12, 44, 'Confidential Policy&Anti-bribery Policy', 1529546561, 0);
INSERT INTO `course_chapter` VALUES (990, 11, 'chapter', 0, 13, 46, 'PPT和Excel技巧培訓', 1530770535, 0);
INSERT INTO `course_chapter` VALUES (1030, 11, 'chapter', 0, 14, 50, 'Business skills', 1533000144, 0);
INSERT INTO `course_chapter` VALUES (1071, 11, 'chapter', 0, 18, 62, '2018年人員管理會議', 1535694767, 0);
INSERT INTO `course_chapter` VALUES (1344, 11, 'chapter', 0, 15, 54, '小項目相關培訓', 1548755253, 0);
INSERT INTO `course_chapter` VALUES (1347, 11, 'chapter', 0, 16, 57, '其它', 1548852220, 0);
INSERT INTO `course_chapter` VALUES (1355, 11, 'chapter', 0, 3, 10, '角色定位', 1548855441, 0);
INSERT INTO `course_chapter` VALUES (1358, 11, 'chapter', 0, 4, 15, '時間管理', 1548856637, 0);
INSERT INTO `course_chapter` VALUES (1384, 11, 'chapter', 0, 19, 69, '2019年人員管理會議', 1551346870, 0);
INSERT INTO `course_chapter` VALUES (1426, 11, 'chapter', 0, 20, 79, '2019年人員管理培訓', 1553075668, 0);
INSERT INTO `course_chapter` VALUES (1636, 11, 'chapter', 0, 21, 99, '考試專區', 1560145776, 0);
INSERT INTO `course_chapter` VALUES (1660, 11, 'unit', 1636, 1, 100, '考試1', 1560415978, 0);
INSERT INTO `course_chapter` VALUES (1663, 11, 'unit', 1636, 2, 103, '考試2', 1560416011, 0);
INSERT INTO `course_chapter` VALUES (1712, 11, 'chapter', 0, 22, 106, '述職分享', 1562937734, 0);

SET FOREIGN_KEY_CHECKS = 1;

實體類:mybatis

@Data
@NoArgsConstructor
public class CourseLesson implements Serializable {


    private Integer id;

    private Integer courseId;

    private Integer chapterId;

    private Integer number;

    private Integer seq;

    private String status;

    private String title;

    private String type;

}
/**
 * 課程章節
 */
@Data
public class CourseChapter {
    private Integer id;

    private Integer courseId;

    private String type;

    private Integer parentId;

    private Integer number;

    private Integer seq;

    private String title;

    private Integer createdTime;

    private Integer copyId;

    private Course course;
}
@Data
@NoArgsConstructor
public class Course implements Serializable {

    private Integer id;

    private String title;

    private String subtitle;

    private String status;

    private String type;

    private Integer maxstudentnum;

    private String showstudentnumtype;

    private String serializemode;

    private List<CourseLesson> courseLessons;


}

 

dao層:app

public interface CourseMapper {

    @Select("select * from course")
    List<Course> selectCourse();

    @Select("select * from course where id = #{id}")
    @Results({
            @Result(property = "id",column = "id",id = true),
            @Result(property = "courseLessons",column = "id",many = @Many(select = "cm.mbs.annotation.CourseLessonMapper.selectByCourseId"))
    })
    List<Course> selectCourseById(String id);

    @Select({
            "<script>",
            "select * from course",
            "<where>",
            "<if test='title != null'> title = #{title}</if>",
            "</where>",
            "</script>"
    })
    List<Course> selectByTitle(@Param("title") String title);

}
public interface CourseLessonMapper {

    @Select("select * from course_lesson")
    List<CourseLesson> selectAll();

    @Select("select * from course_lesson where courseId = #{courseId}")
    List<CourseLesson> selectByCourseId(int courseId);
}
public interface CourseChapterMapper {

    @Select("select * from course_chapter")
    List<CourseChapter> selectAll();

    @Select("select * from course_chapter where id = #{id}")
    @Results({
            @Result(property = "id" ,column = "id"),
            @Result(property = "courses",column = "courseId", one = @One(select = "cm.mbs.annotation.CourseMapper.selectCourseById"))
    })
    List<CourseChapter> selectById(int id);


}

測試:less

public class CourseChapterMapperTest {

    private static SqlSessionFactory sqlSessionFactory;


    @BeforeClass
    public static void init() {
        InputStream is = null;
        try {
            String resource = "mybatis-config.xml";
            is = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testSelectAll(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        CourseChapterMapper mapper = sqlSession.getMapper(CourseChapterMapper.class);
        List<CourseChapter> courseChapters = mapper.selectAll();
        System.out.println(courseChapters.size());
    }

    @Test
    public void testSelectById(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        CourseChapterMapper mapper = sqlSession.getMapper(CourseChapterMapper.class);
        List<CourseChapter> courseChapters = mapper.selectById(22);
        System.out.println(courseChapters.size());
    }

}
public class CourseLessonMapperTest {
    private static SqlSessionFactory sqlSessionFactory;


    @BeforeClass
    public static void init() {
        InputStream is = null;
        try {
            String resource = "mybatis-config.xml";
            is = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Test
    public void testSelectAll(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        CourseLessonMapper mapper = sqlSession.getMapper(CourseLessonMapper.class);
        List<CourseLesson> courses = mapper.selectAll();
        System.out.println(courses.size());
    }
}
public class CourseMapperTest {

    private static SqlSessionFactory sqlSessionFactory;


    @BeforeClass
    public static void init() {
        InputStream is = null;
        try {
            String resource = "mybatis-config.xml";
            is = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @Test
    public void testSelectAll(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
        List<Course> courses = mapper.selectCourse();
        System.out.println(courses.size());
    }
    @Test
    public void testSelectByTitle(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
        List<Course> courses = mapper.selectByTitle("行政培訓");
        System.out.println(courses.size());
    }

    @Test
    public void testSelectCourseById(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        CourseMapper mapper = sqlSession.getMapper(CourseMapper.class);
        List<Course> courses = mapper.selectCourseById("11");
        System.out.println(courses);
    }

}

總結:註解的級聯查詢其實和xml很像,主要使用的註解就是@Results這個註解,和@Result這個註解。ide

若是是一對一的話就使用@One這個註解例如:學習

@Select("select * from course_chapter where id = #{id}")
    @Results({
            @Result(property = "id" ,column = "id"),
            @Result(property = "courses",column = "courseId", one = @One(select = "cm.mbs.annotation.CourseMapper.selectCourseById"))
    })
    List<CourseChapter> selectById(int id);

 

一對多的話就使用@Many這個註解例如:測試

@Select("select * from course where id = #{id}")
    @Results({
            @Result(property = "id",column = "id",id = true),
            @Result(property = "courseLessons",column = "id",many = @Many(select = "cm.mbs.annotation.CourseLessonMapper.selectByCourseId"))
    })
    List<Course> selectCourseById(String id);

 

如何使用註解的時候須要使用動態的sql的話須要借住script這個標籤:例如:ui

@Select({
            "<script>",
            "select * from course",
            "<where>",
            "<if test='title != null'> title = #{title}</if>",
            "</where>",
            "</script>"
    })
    List<Course> selectByTitle(@Param("title") String title);
相關文章
相關標籤/搜索