MyBatis之XML配置文件(一)

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值