MyBatis resultMap与POJO中的构建器

时间:2018-08-19 02:44:35

标签: java mybatis

假设我有一个Java类,代表使用构建器模式的Person:

package com.xyz.domain;

public class Person {

    private final int id;
    private final String firstName;
    private final String middleName;
    private final String lastName;
    private final String address;
    private final String country;

    private Person(PersonBuilder builder) {
        this.id = id;
        this.firstName = builder.firstName;
        this.middleName = builder.middleName;
        this.lastName = builder.lastName;
        this.address = builder.address;
        this.country = builder.country;
    }

    // getters go here

    public static class PersonBuilder {

        private int id;
        private final String firstName;
        private final String lastName;

        private String middleName;
        private String address;
        private String country;

        public PersonBuilder(int id, String firstName, String lastName) {
            this.id = id;
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public PersonBuilder withMiddleName(String middleName) {
            this.middleName = middleName;
            return this;
        }

        public PersonBuilder withAddress(String address) {
            this.address = address;
            return this;
        }

        public PersonBuilder withCountry(String country) {
            this.country = country;
            return this;
        }

        public Person build() {
            return new Person(this);
        }
    }
}

我想以此作为mybatis type中的resultMap

<resultMap id="Person" type="com.xyz.domain.Person">
    <id property="id" column="id" />
    <result property="firstName" column="first_name" />
    <result property="middleName" column="middle_name" />
    <result property="lastName" column="last_name" />
    <result property="address" column="address" />
    <result property="country" column="country" />
</resultMap>

但是,当我调用使用此结果映射的端点时,这会在Spring应用程序中产生500错误。我还尝试将type中的resultMap参数设置为com.xyz.domain.Person.PersonBuilder并得到一个错误。有什么办法可以在不牺牲Person类中的构建器模式的情况下完成这项工作?

2 个答案:

答案 0 :(得分:0)

用@Alias(“ Person”)注释标记POJO。 还要确保在配置myBatis数据连接时,已包含com.xyz.domain软件包来扫描POJO。

答案 1 :(得分:0)

我能够通过像这样更新结果图来解决问题

<resultMap id="Person" type="com.xyz.domain.Person$PersonBuilder">
    <constructor>
        <idArg name="id" column="id" />
        <arg name="firstName" column="first_name" />
        <arg name="lastName" column="last_name" />
    </constructor>
    <result property="middleName" column="middle_name" />
    <result property="address" column="address" />
    <result property="country" column="country" />
</resultMap>

这将创建一个PersonBuilder对象列表,但是很容易遍历该列表并在Java中的每个列表项上调用build()方法:personBuilderList.stream().map(Person.PersonBuilder::build).collect(toList())