mybatis基本用法

来源:互联网 发布:软件 安全性设计文档 编辑:程序博客网 时间:2024/06/14 08:27

xml

可以看作是接口实现类

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- namespace命名空间,等于mapper接口地址--><mapper namespace="com.mybatis.mapper.UserMapper">    <!-- 定义sql片段,提高重用性    id:被引用的唯一标识    经验:在sql片段中不要包括 where     -->    <sql id="query_user_where">        <if test="userCustom!=null">            <if test="userCustom.sex!=null and userCustom.sex!=''">                and user.sex = #{userCustom.sex}            </if>            <if test="userCustom.username!=null and userCustom.username!=''">                and user.username LIKE concat('%', #{name}, '%')            </if>            <if test="ids!=null">                <!-- 使用 foreach遍历传入ids                collection:指定输入 对象中集合属性                item:每个遍历生成对象中                open:开始遍历时拼接的串                close:结束遍历时拼接的串                separator:遍历的两个对象中需要拼接的串                 -->                 <!-- 使用实现下边的sql拼接:                  AND (id=1 OR id=10 OR id=16)                   -->                <foreach collection="ids" item="user_id" open="AND (" close=")" separator="or">                    <!-- 每个遍历需要拼接的串 -->                    id=#{user_id}                </foreach>                <!-- 实现  “ and id IN(1,10,16)”拼接 -->                <!-- <foreach collection="ids" item="user_id" open="and id IN(" close=")" separator=",">                    每个遍历需要拼接的串                    #{user_id}                </foreach> -->            </if>        </if>    </sql>    <!-- 映射关系        type:resultMap最终映射的java对象类型,可以使用别名        id:唯一标识     -->     <resultMap type="user" id="userResultMap">        <!-- id:查询结果集中唯一标识         column:查询出来的列名        property:type指定的pojo类型中的属性名        -->        <id column="id_" property="id"/>        <!-- result:对普通名映射定义 -->        <result column="username_" property="username"/>     </resultMap>    <!-- 用户信息综合查询    #{userCustom.sex}:取出pojo包装对象中性别值    ${userCustom.username}:取出pojo包装对象中用户名称     -->    <select id="findUserList" parameterType="com.mybatis.po.UserQueryVo"             resultType="cn.itcast.mybatis.po.UserCustom">    SELECT * FROM USER    <!-- where可以自动去掉条件中的第一个and -->    <where>        <!-- 引用sql片段 的id,如果refid指定的id不在本mapper文件中,需要前边加namespace -->        <include refid="query_user_where"></include>        <!-- 在这里还要引用其它的sql片段 所以引入的sql片段中不要加where -->    </where>    </select>    <!-- 用户信息综合查询总数    parameterType:输入类型    resultType:输出类型     -->    <select id="findUserCount" parameterType="com.mybatis.vo.UserQueryVo" resultType="int">       SELECT count(*) FROM USER         <where>            <include refid="query_user_where"></include>        </where>    </select>    <!-- 通过id查询用户表的记录 -->    #{}: 占位符    #{id}:其中的id表示接收输入 的参数,参数名称就是id,如果输入 参数是简单类型,#{}中的参数名可以任意,可以value或其它名称    resultType:输出结果映射的java对象类型,select指定resultType表示将单条记录映射成的java对象     -->    <select id="findUserById" parameterType="int" resultType="user">        SELECT * FROM USER WHERE id=#{value}    </select>    <!-- 使用resultMap进行输出映射    resultMap:指定定义的resultMap的id,如果这个resultMap在其它的mapper文件,前边需要加namespace    -->    <select id="findUserByIdResultMap" parameterType="int" resultMap="userResultMap">        SELECT id id_,username username_ FROM USER WHERE id=#{value}    </select>    <!-- 根据用户名称模糊查询用户信息,可能返回多条        ${}:表示拼接sql串,将接收到参数的内容不加任何修饰拼接在sql中,可能会引起 sql注入,一般应用在order by;        ${value}:接收输入 参数的内容,如果传入类型是简单类型,${}中只能使用value;        #{xxx},使用的是PreparedStatement,有类型转换,所以比较安全;        ${xxx},使用字符串拼接,可以SQL注入;        like查询不小心会有漏动,正确写法如下:            Mysql: select * from t_user where name like concat('%', #{name}, '%')                  Oracle: select * from t_user where name like '%' || #{name} || '%'                  SQLServer: select * from t_user where name like '%' + #{name} + '%'     -->    <select id="findUserByName" parameterType="java.lang.String" resultType="com.mybatis.po.User">        <!-- SELECT * FROM USER WHERE username LIKE '%${value}%' -->        SELECT * FROM USER WHERE username LIKE concat('%', #{name}, '%')    </select>    <!-- 添加用户 -->    <insert id="insertUser" parameterType="com.mybatis.po.User">        <!--         将插入数据的主键返回,返回到user对象中        SELECT LAST_INSERT_ID():得到刚insert进去记录的主键值,只适用与自增主键        keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性        order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序        resultType:指定SELECT LAST_INSERT_ID()的结果类型         -->        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">            SELECT LAST_INSERT_ID()        </selectKey>        <!-- #{}中指定pojo的属性名,接收到pojo对象的属性值,mybatis通过OGNL获取对象的属性值 -->        insert into user(username,birthday,sex,address) value(#{username},#{birthday},#{sex},#{address})        <!--         使用mysql的uuid()生成主键        执行过程:        首先通过uuid()得到主键,将主键设置到user对象的id属性中        其次在insert执行时,从user对象中取出id属性值         -->        <!--  <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">            SELECT uuid()        </selectKey>        insert into user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address}) -->    </insert>    <!-- 删除用户 -->    <delete id="deleteUser" parameterType="java.lang.Integer">        delete from user where id=#{id}    </delete>    <!-- 更新用户 -->    <update id="updateUser" parameterType="com.mybatis.po.User">        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}          where id=#{id}    </update></mapper>

mapper

接口
UserMapper.java

package com.mybatis.mapper;import java.util.List;import com.mybatis.po.User;import com.mybatis.po.UserCustom;import com.mybatis.vo.UserQueryVo;public interface UserMapper {    //用户信息综合查询    public List<UserCustom> findUserList(UserQueryVo userQueryVo) throws Exception;    //用户信息综合查询总数    public int findUserCount(UserQueryVo userQueryVo) throws Exception;    //根据id查询用户信息    public User findUserById(int id) throws Exception;    //根据id查询用户信息,使用resultMap输出    public User findUserByIdResultMap(int id) throws Exception;    //根据用户名列查询用户列表    public List<User> findUserByName(String name)throws Exception;    //插入用户    public void insertUser(User user)throws Exception;    //删除用户    public void deleteUser(int id)throws Exception;}

vo

UserQueryVo.java

package com.mybatis.vo;import java.util.List;public class UserQueryVo {    //传入多个id    private List<Integer> ids;    //用户查询条件    private UserCustom userCustom;    public UserCustom getUserCustom() {        return userCustom;    }    public void setUserCustom(UserCustom userCustom) {        this.userCustom = userCustom;    }    public List<Integer> getIds() {        return ids;    }    public void setIds(List<Integer> ids) {        this.ids = ids;    }}

po

UserCustom.java

package com.mybatis.po;public class UserCustom extends User{    //可以扩展用户的信息}

User.java

package com.mybatis.po;import java.util.Date;public class User {    //属性名和数据库表的字段对应    private int id;    private String username;// 用户姓名    private String sex;// 性别    private Date birthday;// 生日    private String address;// 地址    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public Date getBirthday() {        return birthday;    }    public void setBirthday(Date birthday) {        this.birthday = birthday;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }}
0 0