mybatis-xml配置

(一)先配置datasource.properties配置文件:(此步可省略)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/wode?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=admin

 

(二)配置SqlMapConfig.xml

复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="datasource.properties"></properties>    
    <typeAliases>
        <package name="com.wode.pojo"/>
    </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/wode/mapper"/>
    </mappers>
</configuration>
复制代码

(三)创建自己的工具类:

复制代码
package com.wodo.util;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DbUtil {
    private static SqlSessionFactory sessionFactory;
    static{
        InputStream  in= null;
        try {
            in=Resources.getResourceAsStream("SqlMapConfig.xml");
            sessionFactory=new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    public static SqlSession getSession(){
        return sessionFactory.openSession();
    }
}
复制代码

(四)导入相关jar包

(五)mapper中xml的配置

5.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.wode.mapper.UserInfoMapper">
    <resultMap type="UserInfo" id="UserInfo">
        <id property="infoId" javaType="int" column="info_id" />
        <result javaType="java.lang.String" property="nickName" column="nickname" />
    </resultMap>
    <resultMap type="UserInfo" id="UserInfoWithUser">
        <id property="infoId" javaType="int" column="info_id" />
        <result javaType="java.lang.String" property="nickName" column="nickname" />
        <association property="user" column="user_id" javaType="int"
            select="com.wode.mapper.UserMapper.findUserById"></association>
            <!-- 这里我们通过mapper识别符找到userMapper中的findUserById,其实是执行了两次 -->
    </resultMap>
    <!-- 单表查询info数据 -->
    <select id="findUserInfoById" resultMap="UserInfo"
        parameterType="int">
        select * from userinfo where info_id=#{id}
    </select>
    
    <!-- 多表1对1关系查询数据 -->
    <select id="findInfoAndUserById" resultMap="UserInfoWithUser"
        parameterType="int">
        select * from userinfo where info_id=#{id}
    </select>
</mapper>
复制代码
复制代码
<?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.wode.mapper.UserMapper">
 <resultMap id="userMap" type="User" >
      <id property="userId" column="user_id" javaType="int"></id>
      <result property="userName" column="user_name" javaType="java.lang.String"/>
      <result property="userPwd" column="user_pwd" javaType="java.lang.String"/>
  </resultMap>
  
  <resultMap id="userAndInfo" type="User" >
      <id property="userId" column="user_id" javaType="int"></id>
      <result property="userName" column="user_name" javaType="java.lang.String"/>
      <result property="userPwd" column="user_pwd" javaType="java.lang.String"/>
      <association property="info" column="user_id" javaType="UserInfo" 
          select="com.wode.mapper.UserInfoMapper.findUserInfoById"></association>
  </resultMap>
  
    <insert id="addUser" parameterType="User"  useGeneratedKeys="true">
    
        insert into users(user_name,user_pwd) values(#{user.userName},#{user.userPwd})
    </insert>
    <select id="findUserById" resultMap="userMap" parameterType="int">
        select * from users where user_id=#{id}
    </select>
    
    <select id="findUserAndInfoById" resultMap="userAndInfo" parameterType="int">
        select * from users where user_id=#{id}
    </select>
</mapper>
复制代码

 5.2 一对多:

复制代码
<?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.wode.mapper.UserInfoMapper">
    <resultMap type="UserInfo" id="UserInfo">
        <id property="infoId" javaType="int" column="info_id" />
        <result javaType="java.lang.String" property="nickName" column="nickname" />
    </resultMap>

    <resultMap type="UserInfo" id="UserInfoAndUser">
        <id property="infoId" javaType="int" column="info_id" />
        <result javaType="java.lang.String" property="nickName" column="nickname" />
        <association property="user" column="user_id" javaType="int"
            select="com.wode.mapper.UserMapper.findUserById"></association>
    </resultMap>
    <!-- 单表查询info数据 -->
    <select id="findUserInfoById" resultMap="UserInfo"
        parameterType="int">
        select * from userinfo where info_id=#{id}
        <!-- 这里会有问题出现吗?注意查询条件? -->
    </select>
    <select id="findUserInfoById2" resultMap="UserInfo"
        parameterType="int">
        select * from userinfo where user_id=#{id}
    </select>

    <!-- 多对1查询 -->
    <select id="findUserInfoAndUser" resultMap="UserInfoAndUser"
        parameterType="int">
        select * from userinfo where info_id=#{id}
    </select>
</mapper>
复制代码
复制代码
<?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.wode.mapper.UserMapper">
 <resultMap id="userMap" type="User" >
      <id property="userId" column="user_id" javaType="int"></id>
      <result property="userName" column="user_name" javaType="java.lang.String"/>
      <result property="userPwd" column="user_pwd" javaType="java.lang.String"/>
  </resultMap>
  
  <!-- 连表查询 -->
  <resultMap id="userandInfo" type="User" >
      <id property="userId" column="user_id" javaType="int"></id>
      <result property="userName" column="user_name" javaType="java.lang.String"/>
      <result property="userPwd" column="user_pwd" javaType="java.lang.String"/>
      <collection property="info" column="user_id" select="com.wode.mapper.UserInfoMapper.findUserInfoById2"></collection>
  </resultMap>
    <insert id="addUser" parameterType="User"  useGeneratedKeys="true">

        insert into users(user_name,user_pwd) values(#{user.userName},#{user.userPwd})
    </insert>
    <select id="findUserById" resultMap="userMap" parameterType="int">
        select * from users where user_id=#{id}
    </select>
    
    <!-- 一对多查询 -->
    <select id="findUserAndInfoById" resultMap="userandInfo" parameterType="int">
        select * from users where user_id=#{id}
    </select>
    
</mapper>
复制代码

5.3:多对多

复制代码
<?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.wode.mapper.CourseMapper">
    <resultMap type="Course" id="UserAndCourse">
        <id property="id" column="course_id" javaType="int"></id>
        <result property="code" column="course_code" javaType="java.lang.String" />
        <result property="name" column="course_name" javaType="java.lang.String" />
        <collection property="users"  column="course_id" select="findByUser"></collection>
    </resultMap>
    <resultMap type="Course" id="courseMap">
        <id property="id" column="course_id" javaType="int"></id>
        <result property="code" column="course_code" javaType="java.lang.String" />
        <result property="name" column="course_name" javaType="java.lang.String" />
    </resultMap>
    
    <select id="findCourse" resultMap="courseMap" parameterType="int">
        select * from course where course_id=#{id}
    </select>
    <select id="findUserAndCourse" resultMap="UserAndCourse" parameterType="int">
        select * from course where course_id=#{id}
    </select>
    <select id="findByUser" parameterType="int" resultMap="com.wode.mapper.UserMapper.userMap">
        select * from users where user_id in (select user_id from users_course where course_id=#{id})
    </select>
</mapper>
复制代码
复制代码
<?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.wode.mapper.UserMapper">
 <resultMap id="userMap" type="User" >
      <id property="userId" column="user_id" javaType="int"></id>   
      <result property="userName" column="user_name" javaType="java.lang.String"/>
      <result property="userPwd" column="user_pwd" javaType="java.lang.String"/>
      <result property="userType" column="user_type" javaType="int"/>
  </resultMap>
<resultMap type="User" id="userAndCourse">
    <id property="userId" column="user_id" javaType="int"></id>   
      <result property="userName" column="user_name" javaType="java.lang.String"/>
      <result property="userPwd" column="user_pwd" javaType="java.lang.String"/>
      <result property="userType" column="user_type" javaType="int"/>
      <collection property="courses" column="user_id" select="findByCourse"></collection>
</resultMap>

    <insert id="addUser" parameterType="User" keyProperty="user.userId" useGeneratedKeys="true">
        insert into users values(null,#{user.userName},#{user.userPwd},#{user.userType})
    </insert>
    <!-- 得到刚才插入数据库自增长的主键值 -->
    <delete id="delById" parameterType="Integer">
        delete from users where user_id=#{id}
    </delete>
    <update id="updateUserById"  parameterType="String">
    <!-- id为1的数据的名字改为用户需要的 -->
        update users set user_name=#{name} where user_id=1
    </update>
    
    <select id="getUserById" parameterType="Integer" resultMap="userMap" >
        select * from users where user_id=#{id}
    </select>
    <select id="getAllUser"  resultMap="userMap" >
        select * from users 
    </select>
    <!--many to many-->    
    <select id="findUserAndCourse" parameterType="int" resultMap="userAndCourse">
        select * from users where user_id=#{id}
    </select>
    <select id="findByCourse" parameterType="int" resultMap="com.wode.mapper.CourseMapper.courseMap">
        select * from course where course_id in (select course_id from users_course where user_id=#{id})
    </select>
</mapper>
复制代码

5.4:动态sql

复制代码
<?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.wode.mapper.ScoreMapper">
    <sql id="score">id,name,age,className</sql>
    <resultMap type="Score" id="scoreMap">
        <id column="id" javaType="int" property="id"/>
        <result column="name" property="name" javaType="java.lang.String"/>
        <result column="age" property="age" javaType="int"/>
        <result column="className" property="className" javaType="java.lang.String"/>
        <result column="java" property="java" javaType="int"/>
        <result column="web" property="web" javaType="int"/>
        <result column="mysql" property="mysql" javaType="int"/>
    </resultMap>
    <!-- 测试sql标签 的使用 -->
    <select id="findScoreById" parameterType="java.util.Map" resultMap="scoreMap">
        select <include refid="score"/>
        from score where id=#{id} and java=#{java}
    </select>
    
<!-- 根据if语句对数据结果做筛选 -->
    <select id="searchStudent" parameterType="java.util.Map"  resultMap="scoreMap">
            select * from score  where 1=1
            <if test="java!=null">
                and java &gt;=#{java}
            </if>
            <if test="web!=null">
                and web &gt;=#{web}
            </if>
            <if test="mysql!=null">
                and mysql &gt;=#{mysql}
            </if>
    </select>
    <!-- choose  对某科目的及格学生做查询 -->
    <select id="searchStudent2" parameterType="java.lang.String" resultMap="scoreMap">
        select * from score 
        <choose>
            <when test="course=='java'">
                where java &gt;=60
            </when>
            <when test="course=='web'">
                where web &gt;=60
            </when>
            <otherwise>
                where mysql &gt;=60
            </otherwise>
        </choose>
    </select>
    <!-- <where>条件使用
    <select id="searchStudent" parameterType="java.util.Map"  resultMap="scoreMap">
            select * from score 
            <where>
            <if test="java!=null">
                and java &gt;=#{java}
            </if>
            <if test="web!=null">
                and web &gt;=#{web}
            </if>
            <if test="mysql!=null">
                and mysql &gt;=#{mysql}
            </if>
            </where>
    </select>
     -->
    
    <!--  trim
    <select id="searchStudent" parameterType="java.util.Map"  resultMap="scoreMap">
            select * from score  
            <trim prefix="where" prefixOverrides="and|or">
            <if test="java!=null">
                and java &gt;=#{java}
            </if>
            <if test="web!=null">
                and web &gt;=#{web}
            </if>
            <if test="mysql!=null">
                and mysql &gt;=#{mysql}
            </if>
            </trim>
    </select>
    -->
    
    <!-- 测试set -->
    <update id="updateScore" parameterType="java.util.Map">
        update score 
        <set>
            <if test="java != null">
                  java = #{java},
              </if>
              <if test="web != null">
                  web = #{web},
              </if>
              <if test="mysql != null">
                  mysql = #{mysql}
              </if>
        </set>
              where id = #{id}
    </update>
</mapper>
复制代码

5.5:foreach

复制代码
<?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.wode.mapper.UserMapper">
    <resultMap id="userMap" type="User">
        <id property="userId" column="user_id" javaType="int"></id>
        <result property="userName" column="user_name" javaType="java.lang.String" />
        <result property="userPwd" column="user_pwd" javaType="java.lang.String" />
        <result property="userType" column="user_type" javaType="int" />
    </resultMap>

    <select id="getUserById" parameterType="Integer" resultMap="userMap">
        select * from users where user_id=#{id}
    </select>
    
    <!--1:collection要循环的集合 item:集合中的一个元素 open:以什么开始 close:以什么结束separator:循环内容之间以什么分隔 -->
    <select id="findUser"  parameterType="java.util.Map" resultMap="userMap">
        select * from users
        <where>
            user_id in
            <foreach collection="usersId" item="userId" separator="," open="(" close=")" index="">
                #{userId}            
            </foreach>
        </where>
    </select>
</mapper>
复制代码

5.6:二级缓存(sqlsessionFatory)

需在sqlMapconfig.xml中配置:

    <settings>
        <setting name="cacheEnabled" value="true" />
    </settings>

在映射.xml中配置:

<cache />

测试:

复制代码
public class UserService {
    public static void main(String[] args) {
        SqlSession session = DbUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.getUserById(1);
        //session.close(); 1级别关闭之后才写入了二级缓存,如果这样我们不关闭session会这么样呢?-执行了两次
        SqlSession session2 = DbUtil.getSession();
        UserMapper mapper2 = session2.getMapper(UserMapper.class);
        mapper2.getUserById(1);
    }
}
复制代码

如:

复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="datasource.properties"></properties>
    <settings>
        <setting name="cacheEnabled" value="true" />
    </settings>
    <!-- 将我们的pojo注册到配置文件 -->
    <typeAliases>
        <package name="com.wode.pojo" />
    </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/wode/mapper" />
    </mappers>
</configuration>
复制代码
复制代码
<?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.wode.mapper.UserMapper">
<cache />
    <resultMap id="userMap" type="User">
        <id property="userId" column="user_id" javaType="int"></id>
        <result property="userName" column="user_name" javaType="java.lang.String" />
        <result property="userPwd" column="user_pwd" javaType="java.lang.String" />
        <result property="userType" column="user_type" javaType="int" />
    </resultMap>

    <select id="getUserById" parameterType="Integer" resultMap="userMap"  >
        select * from users where user_id=#{id}
    </select>
    
</mapper>
复制代码

 5.7:继承

复制代码
<?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.wode.mapper.PetMapper">
      
      <resultMap id="petMap" type="PetBean">
          <id property="id" column="pet_id" javaType="int"/>
          <result property="name" column="f_name" javaType="java.lang.String"/>
          <discriminator column="f_type" javaType="java.lang.String">
              <case value="dog" resultType="DogBean">
                  <result property="boneNum" column="f_bonenum" javaType="int"/>
              </case>
              <case value="duck" resultType="DuckBean">
                  <result property="fishNum" column="f_fishnum" javaType="int"/>
              </case>
              <case value="cat" resultType="CatBean">
                  <result property="fishNum" column="f_fishnum" javaType="int"/>
                  <result property="mouseNum" column="f_mousenum" javaType="int"/>
              </case>
          </discriminator>
      </resultMap>
      
      
      <select id="getAllPet" resultMap="petMap">
          select * from pet
      </select>
      
      <select id="getAllCat" resultMap="petMap">
          select * from pet where f_type='cat'
      </select>
      
</mapper>
复制代码

 el常用判断表达式:

==、eq、//相等

!=、ne、// 不相等 <、lt、//小于 >、gt、//大于 <=、ge、//小于等于 >=、le。//大于等于

posted @ 2019-03-26 14:12  人情世故  阅读(446)  评论(0编辑  收藏  举报
"不管做什么,只要坚持下去就会看到不一样!在路上,不卑不亢!"