MyBatis圖文並茂講解註解開發一對一查詢

MyBatis的註解實現復雜映射開發

實現復雜關系映射之前我們可以在映射文件中通過配置來實現,使用註解開發後,我們可以使用@Results註解,@Result註解,@One註解,@Many註解組合完成復雜關系的配置

一對一查詢

一對一查詢的模型

一對一查詢的需求:查詢一個用戶信息,與此同時查詢出該用戶對應的身份證信息

一對一查詢的語句

創建數據庫:

-- ----------------------------
-- Table structure for card
-- ----------------------------
DROP TABLE IF EXISTS `card`;
CREATE TABLE `card`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `number` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `pid` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `cp_fk`(`pid`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of card
-- ----------------------------
INSERT INTO `card` VALUES (1, '12345', 1);
INSERT INTO `card` VALUES (2, '23456', 2);
INSERT INTO `card` VALUES (3, '34567', 3);
-- ----------------------------
-- Table structure for classes
-- ----------------------------
DROP TABLE IF EXISTS `classes`;
CREATE TABLE `classes`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of classes
-- ----------------------------
INSERT INTO `classes` VALUES (1, '極地一班');
INSERT INTO `classes` VALUES (2, '極地二班');
-- ----------------------------
-- Table structure for course
-- ----------------------------
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of course
-- ----------------------------
INSERT INTO `course` VALUES (1, '語文');
INSERT INTO `course` VALUES (2, '數學');
-- ----------------------------
-- Table structure for person
-- ----------------------------
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of person
-- ----------------------------
INSERT INTO `person` VALUES (1, '張三', 23);
INSERT INTO `person` VALUES (2, '李四', 24);
INSERT INTO `person` VALUES (3, '王五', 25);
-- ----------------------------
-- Table structure for stu_cr
-- ----------------------------
DROP TABLE IF EXISTS `stu_cr`;
CREATE TABLE `stu_cr`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sid` int(11) NULL DEFAULT NULL,
  `cid` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `sc_fk1`(`sid`) USING BTREE,
  INDEX `sc_fk2`(`cid`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Fixed;
-- ----------------------------
-- Records of stu_cr
-- ----------------------------
INSERT INTO `stu_cr` VALUES (1, 1, 1);
INSERT INTO `stu_cr` VALUES (2, 1, 2);
INSERT INTO `stu_cr` VALUES (3, 2, 1);
INSERT INTO `stu_cr` VALUES (4, 2, 2);
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `NAME` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  `cid` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `cs_fk`(`cid`) USING BTREE
) ENGINE = MyISAM AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1, '張三', 23, 1);
INSERT INTO `student` VALUES (2, '李四', 24, 1);
INSERT INTO `student` VALUES (3, '王五', 25, 2);
INSERT INTO `student` VALUES (4, '趙六', 26, 2);
SET FOREIGN_KEY_CHECKS = 1;

對應的sql語句:

SELECT * FROM card;
SELECT * FROM person WHERE id=#{id};

創建PersonMapper接口

public interface PersonMapper {
    //根據id查詢
    @Select("SELECT * FROM person WHERE id=#{id}")
    public abstract Person selectById(Integer id);
}

使用註解配置Mapper

public interface CardMapper {
    //查詢全部
    @Select("SELECT * FROM card")
    @Results({
            @Result(column = "id",property = "id"),
            @Result(column = "number",property = "number"),
            @Result(
                    property = "p",             // 被包含對象的變量名
                    javaType = Person.class,    // 被包含對象的實際數據類型
                    column = "pid",             // 根據查詢出的card表中的pid字段來查詢person表
                    /*
                        one、@One 一對一固定寫法
                        select屬性:指定調用哪個接口中的哪個方法
                     */
                    one = @One(select = "com.yyl.one_to_one.PersonMapper.selectById")
            )
    })
    public abstract List<Card> selectAll();
}

測試類

public class Test01 {
    @Test
    public void selectAll() throws Exception{
        //1.加載核心配置文件
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        //2.獲取SqlSession工廠對象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3.通過工廠對象獲取SqlSession對象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4.獲取CardMapper接口的實現類對象
        CardMapper mapper = sqlSession.getMapper(CardMapper.class);
        //5.調用實現類對象中的方法,接收結果
        List<Card> list = mapper.selectAll();
        //6.處理結果
        for (Card card : list) {
            System.out.println(card);
        }
        //7.釋放資源
        sqlSession.close();
        is.close();
    }
}

運行結果如下:

一對一配置總結

註解 說明
@Results 封裝映射關系的父註解。
Result[] value():定義瞭 Result 數組
@Result 封裝映射關系的子註解。
column 屬性:查詢出的表中字段名稱
property 屬性:實體對象中的屬性名稱
javaType 屬性:被包含對象的數據類型
one 屬性:一對一查詢固定屬性
@One 一對一查詢的註解。
select 屬性:指定調用某個接口中的方法

到此這篇關於MyBatis圖文並茂講解註解開發一對一查詢的文章就介紹到這瞭,更多相關MyBatis一對一查詢內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: