Mybatis

  • Mybatis简介
    MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记录。
  • xml配置


<configuration>
    
    <properties resource="db.properties">properties>
    
        
    
    
	<setting name="lazyLoadingEnabled" value="true"/>
	
	<setting name="aggressiveLazyLoading" value="false"/>

    <typeAliases>
        
        
        
        <package name="com.mybatis.pojo">package>
    typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
            
            
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            dataSource>
        environment>
    environments>
    <mappers>
        
        
        
        
        <package name="com.mybatis.mapper">package>
    mappers>
configuration>
  • 增删改查实例
<select id="selectPerson" parameterType="int" resultType="hashmap">
  SELECT * FROM PERSON WHERE ID = #{id}
select>

<insert id="insertAuthor" parameterType="domain.blog.Author">
  insert into Author (id,username,password,email,bio)
  values (#{id},#{username},#{password},#{email},#{bio})
insert>

<update id="updateAuthor" parameterType="domain.blog.Author">
  update Author set
    username = #{username},
    password = #{password},
    email = #{email},
    bio = #{bio}
  where id = #{id}
update>

<delete id="deleteAuthor" parameterType="int">
  delete from Author where id = #{id}
delete>
  • 自定义返回类型 resultMap
  1. 属性
    type:确定封装的返回值类型
    id:resultMap唯一标识
  2. 标签
    指定主键列的封装规则
    id 定义主键会底层有优化
    result 普通列
    column:指定哪一列
    property:指定对应的javaBean属性

普通封装

<resultMap type="com.atguigu.mybatis.bean.Employee" id="MyEmp">
    <id column="id" property="id"/>
    
    <result column="name" property="name"/>
    
    <result column="age" property="age"/>
    <result column="sex" property="sex"/>
resultMap>

多表联查

<resultMap type="com.test.mybatis.po.Student" id="MySchoolEmp">
    <id column="id" property="id"/>
    
    <result column="name" property="name"/>
    <result column="age" property="age"/>
    <result column="sex" property="sex"/>
    <association property="school" javaType="com.test.mybatis.po.School">
        <id column="cId" property="id"/>
        <result column="cName" property="name"/>
    association>
resultMap>

返回类型包含链表

<resultMap type="com.test.mybatis.po.School" id="myMap1">
<id column="id" property="id"/>
<result column="name" property="name"/>
<collection property="stus" ofType="com.test.mybatis.po.Student">
    <id column="sId" property="id"/>
    <result column="sName" property="name"/>
    <result column="age" property="age"/>
    <result column="sex" property="sex"/>
collection>
resultMap>

<select id="getSchoolByIdPlus" resultMap="myMap1">
    select sc.id id, sc.name name, st.id sId, st.name sName, st.age age, st.sex sex from school sc left join student st on sc.id = st.s_id where sc.id = #{id}
select>
  • 获取sqlsession
public class Main {
    private SqlSession session;

    @Before
    public void init(){
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = 
            				new SqlSessionFactoryBuilder().build(inputStream);
            this.session = sqlSessionFactory.openSession(true);
            //true: 设置自动提交
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void test(){
        UserMapper mapper = session.getMapper(UserMapper.class);
        //todo
        //测试
    }

    @After
    public void   destroy(){
        session.close();
    }

}
  • 动态sql
    • if
    • choose (when, otherwise)
    • trim (where, set)
    • foreach
<select id="getStudentByConditionIf" resultType="com.test.mybatis.po.Student">
    select * from student
    
      
    <where>
        <if test="id != null && id != 0">
        id = #{id}
        if>
        <if test="name != null && name != ''">
            and name = #{name}
        if>
        <if test="age != null">
            and age = #{age}
        if>
        <if test="sex == "" or sex == """>
            and sex = #{sex}
        if>
    where> 
select>
<select id="getStudentByConditionTrim" resultType="com.test.mybatis.po.Student">
    select * from student
    <trim prefix="where" suffixOverrides="and">
        <if test="id != null && id != 0">
            id = #{id} and
        if>
        <if test="name != null && name != ''">
            name = #{name} and
        if>
        <if test="age != null">
            age = #{age} and
        if>
        <if test="sex == "" or sex == """>
            sex = #{sex}
        if>
    trim> 
select>

trim属性

  1. prefix="":前缀:trim标签体中是整个字符串拼串后的结果。prefix给拼串后的整个字符串加一个前缀
  2. prefixOverrides="":前缀覆盖: 去掉整个字符串前面多余的字符
  3. suffix="":后缀suffix给拼串后的整个字符串加一个后缀
  4. suffixOverrides="":后缀覆盖:去掉整个字符串后面多余的字符

choose:类似于switch

<select id="getStudentByConditionChoose" resultType="com.test.mybatis.po.Student">
    select * from student
    <where>
        <choose>
            <when test="id != null">
                id = #{id}
            when>
            <when test="name != null">
                name = #{name}
            when>
            <when test="age != null">
                age = #{age}
            when>
            <otherwise>
                sex = ""
            otherwise>
        choose>
    where>
select>

set:用于去掉最后的 ,

<update id="setStudent">
    update student
    <!-- 通过set标签设置 -->
    
    <!-- 通过trim标签设置 -->
    <trim prefix="set" suffixOverrides=",">
        <if test="name != null && name != ''">
            name = #{name},
        if>
        <if test="age != null">
            age = #{age},
        if>
        <if test="sex == "" or sex == """>
            sex = #{sex}
        if>
    trim>
    where id=#{id} 
update>

foreach

  1. collection:指定要遍历的集合:
  2. item:将当前遍历出的元素赋值给指定的变量
  3. separator:每个元素之间的分隔符
  4. open:遍历出所有结果拼接一个开始的字符
  5. close:遍历出所有结果拼接一个结束的字符
  6. index:索引。遍历list的时候是index就是索引,item就是当前值,遍历map的时候index表示的就是map的key,item就是map的值
  7. #{变量名}就能取出变量的值也就是当前遍历出的元素
<select id="getStudentByConditionForeach"
        resultType="com.test.mybatis.po.Student">
    select * from student 
	<foreach collection="list" item="item_id" separator="," open="where id in(" 
             close=")">
        #{item_id}
    foreach>
select>

  • 批量插入
<insert id="insertStudent">
    insert into student(name,age,sex,s_id) values
    <foreach collection="stus" item="stu" separator=",">
        (#{stu.name},#{stu.age},#{stu.sex},#{stu.school.id})
    foreach>
insert>

你可能感兴趣的:(Mybatis)