Mybatis的n对n的Mapper问题
2021-03-19 本文已影响0人
zhglance
1.一对多:
场景设置:
一个计划(Plan)下有多个任务(Task),即一对多的关系
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 单元测试类: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));
}
}