Mbatis是一个ORM框架,可以用XML配置文件或注解映射SQL语句,映射文件是MyBatis框架的核心,本文主要讲述XML 映射文件的结构和使用方法。
一、SQL映射文件
SQL映射文件就是mapperxml配置文件,主要实现SQL语句的配置和映射,同时实现JAVA 的POJO对象与数据库中的表和字段进行映射联系的功能。
1、mapper.xml的结构
以student 数据表为例,具体结构可以参看专栏的相关文章,下面是创建的StudentMapper.xml示例,代码如下:
<?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="org.weiz.example01.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="org.weiz.example01.model.Student">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
</resultMap>
<select id="selectAll" resultMap="BaseResultMap">
SELECT * FROM student
</select>
<select id="selectOne" parameterType="Long" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List" />
FROM student
WHERE id= #{id}
</select>
<sql id="Base_Column_List">
id,name,sex,age
</sql>
<insert id="insert" parameterType="org.weiz.example01.model.Student">
insert into student (name,sex,age) values (#{name},#{sex},#{age})
</insert>
<update id="update" parameterType="org.weiz.example01.model.Student">
UPDATE student
SET
<if test="name !=null">name=#{name},</if>
<if test="sex !=null">sex=#{sex},</if>
age=#{age}
WHERE id=#{id}
</update>
<delete id="delete" parameterType="Long">
DELETE FROM student
WHERE id=#{id}
</delete>
<resultMap id="StudentAndClassMap" type="org.weiz.example01.model.Student">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<!--association用户关系映射,查询单个完整对象-->
<association property="classes"
javaType="org.weiz.example01.model.Classes">
<id column="id" property="id" />
<result column="class_name" property="name" jdbcType="VARCHAR"/>
<result column="memo" property="memo" jdbcType="VARCHAR" />
</association>
</resultMap>
<select id="selectStudentAndClass" parameterType="Long"
resultMap="StudentAndClassMap">
SELEC