mybatis总结

    xiaoxiao2025-07-25  5

    1.字段名与实体属性名不相同

    在实际的开发中,数据库的字段名很多时候是和实体属性名不相同的,要实现字段的映射就成为了一个问题。

    这里提供了两个解决办法。

    通过sql语句中定义别名解决字段名和属性名映射关系

    使用mybatis提供的解决方式:通过<resultMap>来映射字段名和实体类属性名的一一对应关系

    代码如下:

    <span style="font-size:18px;font-weight: normal;"><resultMap type="me.gacl.domain.Order" id="orderResultMap"> <!-- 用id属性来映射主键字段 --> <id property="id" column="order_id"/> <!-- 用result属性来映射非主键字段 --> <result property="orderNo" column="order_no"/> <result property="price" column="order_price"/> </resultMap></span> 2.关联查询

    一对一关联

    使用mybatis中的association,它的属性有: property:对象属性的名称 javaType:对象属性的类型 column:对应外键字段名称 select:使用另一个查询封装的结果 xml配置如下: 方法一:嵌套结果 <pre name="code" class="html"><resultMap type="me.gacl.domain.Classes" id="ClassResultMap"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="me.gacl.domain.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> </resultMap> 方法二:嵌套查询 <pre name="code" class="html"> </pre><pre name="code" class="html"><resultMap type="me.gacl.domain.Classes" id="ClassResultMap2"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" select="getTeacher"/> </resultMap>

    一对多关联

         使用的标签和一对一一样

    代码如下:

    方法一:嵌套结果

    <span style="font-weight: normal;"><resultMap type="me.gacl.domain.Classes" id="ClassResultMap3"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="me.gacl.domain.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <!-- ofType指定students集合中的对象类型 --> <collection property="students" ofType="me.gacl.domain.Student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultMap></span>方法二:嵌套查询

    <span style="font-weight: normal;"><span style="font-size:18px;"><resultMap type="me.gacl.domain.Classes" id="ClassResultMap4"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="me.gacl.domain.Teacher" select="getTeacher2"></association> <collection property="students" ofType="me.gacl.domain.Student" column="c_id" select="getStudent"></collection> </resultMap></span></span> 3.调用存储过程

    不多说直接上代码: xml配置文件 <span style="font-size:18px;"><select id="getUserCount" parameterMap="getUserCountMap" statementType="CALLABLE"> CALL mybatis.ges_user_count(?,?) </select></span> <span style="font-size:18px;"></span><pre name="code" class="html"><parameterMap type="java.util.Map" id="getUserCountMap"> <parameter property="sexid" mode="IN" jdbcType="INTEGER"/> <parameter property="usercount" mode="OUT" jdbcType="INTEGER"/> </parameterMap>
    转载请注明原文地址: https://ju.6miu.com/read-1301038.html
    最新回复(0)