[3] resultMap結果セットのマッピング

5.属性名とフィールド名の間の不整合の問題を解決します

1.具体例

pojoエンティティクラス:

public class User {
    
    

    private Integer uid;
    private String username;
    private String pwd;
}

データベース対応フィールド:

ここに画像の説明を挿入

テスト出力結果:

    @Test
    public void getUserByID(){
    
    
        SqlSession sqlSession;
        try {
    
    
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            User user = mapper.getUserByID(2);
            System.out.println(user);
        }finally {
    
    
            MybatisUtils.closeSqlSession();
        }
    }

ここに画像の説明を挿入

これは、フィールドが整列されていない場合に発生します。

2.解決策

1.エイリアスを作成します

    <select id="getUserByID" parameterType="int" resultMap="UserMap">
        select uid,username,password as pwd from users where uid = #{id}
    </select>

2、resultMap

結果セットのマッピング

uid  username  pwd
uid  username  password
    <!--结果集映射-->
    <resultMap id="UserMap" type="User">
        <!--colunm数据库中的字段,properties实体类中的属性-->
        <result column="uid" property="id"/>
        <result column="username" property="name"/>
        <result column="password" property="pwd"/>
    </resultMap>
    <select id="getUserByID" parameterType="int" resultMap="UserMap">
        select * from users where uid = #{id}
    </select>
  • resultMap 要素は、MyBatisで最も重要で強力な要素です。
  • ResultMapの設計アイデアは、単純なステートメントの構成をゼロにすることであり、より複雑なステートメントの場合は、ステートメント間の関係のみを記述する必要があります。
  • ResultMap 最良の部分は、あなたはすでにそれをよく知っていますが、それらを明示的に使用する必要がないということです。

おすすめ

転載: blog.csdn.net/weixin_43215322/article/details/109546311