mybatis-xml配置

 

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

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.xmlmysql

<?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>

(三)建立本身的工具類:web

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包sql

(五)mapper中xml的配置數據庫

5.1:一對一apache

<?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:多對多session

<?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:動態sqlmybatis

<?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:foreachapp

<?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。//大於等於

相關文章
相關標籤/搜索