Mybatis plus 高级映射

正文索引 [隐藏]

一对一

假设现有有A表(test_one),B表(test_two) 他们的建表语句分别为

CREATE TABLE `test_one` (
`one_id` int(11) NOT NULL AUTO_INCREMENT,
`one_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`one_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

CREATE TABLE `test_two` (
`two_id` int(11) NOT NULL AUTO_INCREMENT,
`two_name` varchar(255) DEFAULT NULL,
`two_to_one_id` int(11) DEFAULT NULL,
PRIMARY KEY (`two_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

那我们Java对象如何设计呢,很简单
@Setter
@Getter
@ToString
public class TestOne {
private Integer oneId;
private String oneName;
private TestTwo testTwo;
}
@Setter
@Getter
class TestTwo {
private Integer twoId;
private String twoName;
}

sql如何写呢?有两种方式,因为是一对一,比较简单,最简单的方式就是同时查两张表,然后根据字段相同即可

但是xml写法需要注意


<resultMap id="baseResult" type="me.zhengjie.modules.blog.domain.TestOne">
<id column="one_id" property="oneId" />
<result column="one_name" property="oneName" />
<association property="testTwo" javaType="me.zhengjie.modules.blog.domain.TestTwo">
<id column="two_id" property="twoId" />
<result column="two_name" property="twoName" />
</association>
</collection>
</resultMap>

然后写出来的sql写成resultMap即可

示例

SELECT	A.*,B.*	FROM test_one as A

LEFT JOIN test_two as B on B.two_to_one_id = A.one_id
WHERE A.one_id = #{id}

一对多

假设现有有A表(test_one),C表(test_three) 他们的建表语句分别为

CREATE TABLE `test_one` (
`one_id` int(11) NOT NULL AUTO_INCREMENT,
`one_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`one_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

CREATE TABLE `test_three` (
`three_id` int(11) NOT NULL AUTO_INCREMENT,
`three_name` varchar(255) DEFAULT NULL,
`three_to_one_id` int(11) DEFAULT NULL,
PRIMARY KEY (`three_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

同上,Java如何设计呢,还是很简单
@Setter
@Getter
@ToString
public class TestOne {
private Integer oneId;
private String oneName;
private List TestThrees;
}
@Setter
@Getter
class TestThree {
private Integer threeId;
private String threeName;
}

xml里面的resultMap如何写呢?不难
<resultMap id="baseResult" type="me.zhengjie.modules.blog.domain.TestOne">
<id column="one_id" property="oneId" />
<result column="one_name" property="oneName" />
<collection property="testThrees" ofType="me.zhengjie.modules.blog.domain.TestThree">
<id column="three_id" property="threeId" />
<result column="three_name" property="threeName" />
</collection>
</resultMap>