如何在Mybatis(Java)中创建示例Map中的两个相同内部类

3vpjnl9f  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(191)

我使用类Hand来保存数据。它包含两个相同的内部类Card,也就是说两个Card组成一个Hand。如下所示:

public class Card {
    private Integer id;
    private Integer number;
    private Integer color;

    public Card() {}
    public Card(int number, int color) {
        this.number = number;
        this.color = color;
    }
public class Hand {

    private Integer id;

    private Card card1,card2;

    public Hand() {}
    public Hand(Card a, Card b) {
        card1 = a;
        card2 = b;
    }
}

然后我将Mapxml做成这样:

<resultMap id="handMap" type="com.company.handsmap.Hand">
        <id column="id" property="id"/>
        <association property="card1" resultMap="cardMap"/>
        <association property="card2" resultMap="cardMap"/>
    </resultMap>

    <resultMap id="cardMap" type="com.company.handsmap.Card">
        <id column="id" property="id"/>
        <result column="number" property="number"/>
        <result column="color" property="color"/>
    </resultMap>

    <select id="getAllHand" resultMap="handMap">
        SELECT
        *
        FROM Hand H
        LEFT JOIN Card c1 ON H.card1_id = c1.id
        LEFT JOIN Card c2 ON H.card2_id = c2.id
    </select>

然后我使用Map如下,它似乎得到一些错误:Debugging the bug
如所示,Hand获得了正确的Card 1,但在Card 2中获得了null
如果我跑了

SELECT
        *
        FROM Hand H
        LEFT JOIN Card c1 ON H.card1_id = c1.id
        LEFT JOIN Card c2 ON H.card2_id = c2.id

在数据库中,我可以得到正确的结果如下:SQL results
谁能告诉我问题出在哪里,我该怎么解决它?非常感谢!

osh3o9ms

osh3o9ms1#

我像下面这样更改mapper.xml,它会得到正确的结果

<resultMap id="cardMap1" type="com.company.handsmap.Card">
        <id column="id" property="id"/>
        <result column="c1number" property="number"/>
        <result column="c1color" property="color"/>
    </resultMap>

    <!--Create another Map for Card2-->
    <resultMap id="cardMap2" type="com.company.handsmap.Card">
        <id column="id" property="id"/>
        <result column="c2number" property="number"/>
        <result column="c2color" property="color"/>
    </resultMap>

    <select id="getAllHand" resultMap="handMap">
        SELECT
        H.*,
        c1.id as c1id, c1.number as c1number, c1.color as c1color,
        c2.id as c2id, c2.number as c2number, c2.color as c2color
        FROM Hand H
        LEFT JOIN Card c1 ON H.card1_id = c1.id
        LEFT JOIN Card c2 ON H.card2_id = c2.id
    </select>

它需要两个cardMap,并确保它们都能正确地从数据库列中获取数据

相关问题