1.一對(duì)多:
場(chǎng)景設(shè)置:
一個(gè)計(jì)劃(Plan)下有多個(gè)任務(wù)(Task),即一對(duì)多的關(guān)系
1.1 TaskEntity.java
import lombok.Data;
@Data
public class TaskEntity {
private int id;
private int planId;
private String missionId;
}
1.2 PlanEntity.java
import lombok.Data;
import java.util.List;
@Data
public class PlanEntity {
private int id;
private String planName;
private List<TaskEntity> tasks;
}
1.3 PlanMapper.java
@Repository
public interface PlanMapper extends MybatisSimpleBaseMapper<PlanEntity,Integer> {
PlanEntity selectById(@Param("id") Integer id);
}
1.4 TaskMapper.java
import java.util.List;
public interface TaskMapper extends MybatisSimpleBaseMapper<TaskEntity, Integer> {
List<TaskEntity> selectByPlanId(@Param("planId") int planId);
}
1.5 TaskMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="TaskMapper">
<resultMap id="BaseResultMap"
type="TaskEntity">
<id column="id" jdbcType="INT" property="id"/>
<result column="plan_id" jdbcType="VARCHAR" property="planId"/>
<result column="mission_id" jdbcType="VARCHAR" property="missionId"/>
</resultMap>
<select id="selectByPlanId" resultMap="BaseResultMap">
select *
from task
where plan_id = #{planId}
</select>
</mapper>
1.6 PlanMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="PlanMapper">
<resultMap id="BaseResultMap" type="PlanEntity">
<id column="id" jdbcType="INTEGER" property="id"/>
<result column="plan_name" jdbcType="VARCHAR" property="planName"/>
<collection property="tasks" select="TaskMapper.selectByPlanId" column="id"/>
</resultMap>
<select id="selectById" resultMap="BaseResultMap">
select *
from plan
where id = #{id}
</select>
</mapper>
1.7 單元測(cè)試類:PlanMapperTest.java
@Setter
@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ApplicationLoader.class)
@WebAppConfiguration
public class PlanMapperTest {
@Autowired
private PlanMapper planMapper;
@Test
public void selectById() {
PlanEntity planEntity = planMapper.selectById(168);
log.info("planEntity:{}", JSON.toJSONString(planEntity));
}
}