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的高封装性使得开发速度很快