Mybatis XML映射文件
mybatis为聚焦于SQL而构建,SQL映射文件常用的顶级元素如
- resultMap,是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象。
- insert,映射插入语句
- update, 映射更新语句
- delete , 映射删除语句
- select , 映射查询语句
1)简单的单表映射文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mybatis.bean.userMapper"> <select id="getUser" parameterType="int" resultType="com.mybatis.bean.User"> select * from users where id=#{id} </select> <insert id="insertUser" parameterType="com.mybatis.bean.User"> insert into users(name,age) values(#{name},#{age}); </insert> <update id="updateUser" parameterType="com.mybatis.bean.User"> update users set name=#{name} ,age=#{age} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> delete from users where id=#{id} </delete> <select id="allUser" resultType="com.mybatis.bean.User"> select * from users </select> </mapper>
Java对象
public class User { private int id; private String name; private int age; public int getId() { return id; } public String getName() { return name; } public int getAge() { return age; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } }
2)结果映射resultMap 元素是 MyBatis 中最重要最强大的元素。当列名和属性名没有精确匹配,可以在SELECT语句中对列使用别名,或配置显式的结果映射。
Java对象
public class Classes { private int id; private String name; private Teacher teacher; // 省略 }
resultMap映射文件、关联对象
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.mybatis.bean.ClassMapper"> <select id="getClass" parameterType="int" resultMap="ClassResultMap"> select * from class c,teacher t where c.teacher_id = t.t_id and c.c_id=#{id} </select> <resultMap id="ClassResultMap" type="classes"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> </resultMap> </mapper>
集合配置
<collection property="posts" ofType="domain.blog.Post"> <id property="id" column="post_id"/> <result property="subject" column="post_subject"/> <result property="body" column="post_body"/> </collection>