mybatis使用笔记(一)

1 关系 配置是注意顺序

result ——->association———>collection

2 resultMap

很灵活,一个namespace下可以有多个resultMap,不同namespace下的resultMap可以互相使用

3 枚举

< result column="type" property="type" typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler" />

枚举的配置
在插入时${}可以执行传入参数的方法

INSERT INTO table (id,type) VALUES (#{id},${type==null?'null':type.ordinal()})

#{}是可以防注入攻击的,能用 # {} 的地方尽量不用 $ { }
#{}内不可以执行java方法,而 \${}内是可以的

4 collection和我association关系配置

collection对应多
association对应一
(一)

<resultMap id="teacher" type="taskInfo">
    <result column="id" jdbcType="VARCHAR" property="id" />
    <result column="home_id" jdbcType="VARCHAR" property="homeId" />
    其他字段配置就不写了
    <association column="home_id" property="home" javaType="Home" select="getHome"></association>
    <collection property="students" ofType="Student" column="id" javaType="ArrayList" select="getStudent"></collection>
</resultMap>
<select id="getStudent" resultMap="">
        select id,name from student_table where id=#{id}
</select>
<select id="getHome" resultMap="">
        select id,name from home_table where id=#{homeId}
</select>

这种方式很灵活
collection或association中配置的select可以调用其他命名空间下的
< select >< /select>中的resultMap也可以调用其他命名空间下的
这种配置方式可以使在查询的时候,只要有对应的id或home_id字段,自动执行查询。
如果是树结构(关联自己的字段)就可以进行递归查询了
也可以使用另一种方式配置
(二)

<resultMap id="teacher" type="taskInfo">
    <result column="id" jdbcType="VARCHAR" property="id" />
    <result column="home_id" jdbcType="VARCHAR" property="homeId" />
    其他字段配置就不写了
    <association column="home_id" property="home" javaType="Home" >
        <result column="id" jdbcType="VARCHAR" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
    </association>
    <collection property="students" ofType="Student" column="id" javaType="ArrayList" >
        <result column="id" jdbcType="VARCHAR" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
    </collection>
</resultMap>

这种方式不会自动查询,只是把查询到的结果封装成对象

我一般使用第一种配置方式,因为不需要写复杂的sql。第二种关联的表多的话将是一件很痛苦的事情

5 mybatis与hibernate

mybatis的关系配置是在配置文件中,可以很灵活,你想怎么配就怎么配
hibernate配置关系对应的是实体类,不如mybatis灵活,hibernate的高封装性使得开发速度很快

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tcoding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值