欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Mybatis XML映射文件

程序员文章站 2023-04-04 11:38:44
mybatis为聚焦于SQL而构建,SQL映射文件常用的*元素如 resultMap,是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象。 insert,映射插入语句 update, 映射更新语句 delete , 映射删除语句 select , 映射查询语句 1)简单的单表映射文件 ......

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>

 

参考文献:mybatis官网