关于mybatis的一对一映射问题

有两个数据表部门和人物,此处我没有为person表建立外键:
1.png

2.png

对应的类:

@Data   //lombok
public class Department {
    private Integer depid;
    private String depname;
}
@Data
public class Person {
    private Integer id;
    private String name;
    private Date birthday;
    private Integer departmentid;

    private Department department;

}

这是映射文件(初次学习mybatis,不清楚这样写映射是否正确):

<mapper namespace="com.on1.datahandler.mapper.PersonMapper">
    <resultMap id="personMap" type="Person">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="birthday" column="birthday"/>
        <result property="departmentid" column="departmentid"/>
        <!-- 一对一-->
        <association property="department" column="departmentid" javaType="Department">
            <id property="depid" column="id"/>
            <result property="depname" column="name"/>
        </association>
    </resultMap>

    <select id="getAllPersonAndDepartment" resultMap="personMap">
       select p.*, d.id as depid, d.name as depname
        from person p, department d
        where  d.id=p.departmentid;
    </select>

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class DatahandlerApplicationTests {

    @Autowired
    DataSource dataSource;

    @Autowired
    PersonMapper personMapper;

    @Autowired
    DepartmentMapper departmentMapper;

    @Test
    public void contextLoads() throws SQLException {
        List<Person> people = personMapper.getAllPersonAndDepartment();
        for(int i = 0; i < people.size(); i++) {
            System.out.println(people.get(i));
        }

    }

}

这是我的输出,问题出现在打印的部门depid和depname是错误的。
3.png

想请教下我是哪里出现问题了?
另外我还想问一下,我在参照教学视频时,编写getAllPersonAndDepartment的SQL语句中,使用到了as,在这里as除了别名的作用外,还有什么作用?

阅读 2.4k
2 个回答
新手上路,请多包涵

移除掉column="departmentid"试试?如下:

        <association property="department" javaType="Department">
            <id property="depid" column="id"/>
            <result property="depname" column="name"/>
        </association>

as 起别名,用于匹配property属性

另外,多说几句,select后面不用添加;,并且在实际过程中,这种嵌套写法几乎不会出现,表字段也几乎不会很少会出现重名状态。

这是我配的一个日志文件在控制台里输出的信息,不知道有没有帮助:

1.png

我使用的是Springboot2.2.0,mysql8.0.17

1.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进