027-MyBatis相关配置模板

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="db.properties" >
        <!-- 在properties内部用property定义属性 -->
        <!-- 如果外部配置文件有该属性,则内部定义属性被外部属性覆盖 -->
        <property name="jdbc.username" value="root123" />
        <property name="jdbc.password" value="root123" />
    </properties>
    
    <!-- 别名定义 -->
    <typeAliases>
        <!-- 单个别名定义 -->
        <typeAlias alias="user" type="com.test.mybatis.pojo.User" />
        <!-- 批量别名定义,扫描整个包下的类,别名为类名(大小写不敏感),头字母大小写都可以 -->
        <package name="com.test.mybatis.pojo"/>
        <package name="其他包"/>
    </typeAliases>
    
    
    <!-- 和spring整合后 environments配置将废除 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理 -->
            <transactionManager type="JDBC" />
            <!-- 数据库连接池 -->
            <dataSource type="POOLED">
                <!-- <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url"
                    value="jdbc:mysql://39.105.94.154:3306/mybatis?characterEncoding=utf-8" />
                <property name="username" value="tom" />
                <property name="password" value="tom" /> -->
                
                <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>
        <mapper resource="sqlmap/User.xml"/>
        <mapper resource="mapper/UserMapper.xml"/>
        
        <!-- mapper的其它配置方式  -->
        <!-- 
            方式1 :使用mapper接口类路径
            <mapper class="com.test.mybatis.mapper.UserMapper"/>
            注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。
        -->
        
        <!-- 方式2:注册指定包下的所有mapper接口
            <package name="com.test.mybatis.mapper"/>
            注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。
         -->
    </mappers>
</configuration>

mapper.xml映射文件

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

<!-- namespace:命名空间,用于隔离sql,还有一个很重要的作用,后面会讲 -->
<mapper namespace="test">
    <!-- 根据id查询用户 -->
    <select id="queryUserById" parameterType="Integer" resultType="com.test.mybatis.pojo.User">
        <!-- id:statement的id 或者叫做sql的id-->
        <!-- parameterType:声明输入参数的类型 -->
        <!-- resultType:声明输出结果的类型,应该填写pojo的全路径 -->
        <!-- #{}:输入参数的占位符,相当于jdbc的? -->
        select * from user where id = #{id}
    </select>
    
    <!-- 实现根据用户名模糊查询用户 -->
    <!-- 如果返回多个结果,mybatis会自动把返回的结果放在list容器中 -->
    <!-- resultType的配置和返回一个结果的配置一样 -->
    <select id="queryUserByUsername1" parameterType="String" resultType="com.test.mybatis.pojo.User">
        select * from user where username like #{username}
    </select>
    
    <!-- 如果传入的参数是简单数据类型,${}里面必须写value -->
    <select id="queryUserByUsername2" parameterType="String" resultType="com.test.mybatis.pojo.User">
        select * from user where username like '%${value}%'
    </select>
    
    <!-- 添加用户 -->
    <!-- 
        #{username}可以看成是getUsername方法,从User中取出。
     -->
    <insert id="insertUser" parameterType="com.test.mybatis.pojo.User">
        <!-- selectKey 标签实现主键返回 -->
        <!-- keyColumn:主键对应的表中的哪一列 -->
        <!-- keyProperty:主键对应的pojo中的哪一个属性 -->
        <!-- order:设置在执行insert语句前执行查询id的sql,还是在执行insert语句之后执行查询id的sql -->
        <!-- resultType:设置返回的id的类型 -->
        <selectKey keyColumn="id" keyProperty="id" order="AFTER" resultType="Integer">
            select last_insert_id()
        </selectKey>
        insert into user
        (username,birthday,sex,address) values 
        (#{username},#{birthday},#{sex},#{address})
    </insert>
    
    <!-- 修改用户 -->
    <update id="updateUser" parameterType="com.test.mybatis.pojo.User">
        update user
        set
        username=#{username},birthday=#{birthday}
        where 
        id=#{id}
    </update>
    
    <!-- 删除用户 -->
    <delete id="deleteUserById" parameterType="Integer">
        delete from user where
        id=#{id}
    </delete>
</mapper>

数据库database.properties

这个主要是给properties标签使用的

<properties resource="database.properties" ></properties>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://39.105.94.154:3306/mybatis?characterEncoding=utf-8
jdbc.username=tom
jdbc.password=tom

Mapper动态代理方式的映射文件

Mapper接口开发需要遵循以下规范:

1、 Mapper.xml文件中的namespacemapper接口的类路径相同。

2、 Mapper接口方法名和Mapper.xml中定义的每个statementid相同

3、 Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql parameterType的类型相同

4、 Mapper接口方法的输出参数类型和mapper.xml中定义的每个sqlresultType的类型相同

 

<?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">
<!-- namespace:命名空间,用于隔离sql -->
<!-- 还有一个很重要的作用,使用动态代理开发DAO,1. namespace必须和Mapper接口类路径一致 -->
<mapper namespace="com.test.mybatis.mpper.IUserMpper">
    <!-- 根据用户id查询用户 -->
    <!-- 2. id必须和Mapper接口方法名一致 -->
    <!-- 3. parameterType必须和接口方法参数类型一致 -->
    <!-- 4. resultType必须和接口方法返回值类型一致 -->
    <select id="queryUserById" parameterType="Integer" resultType="user">
        select * from user where id = #{id}
    </select>
    <!-- 根据用户名查询用户 -->
    <select id="queryUserByUsername" parameterType="String" resultType="com.test.mybatis.pojo.User">
        select * from user where username like '%${value}%'
    </select>
    <!-- 保存用户 -->
    <insert id="saveUser" parameterType="com.test.mybatis.pojo.User">
        insert into user
        (username,birthday,sex,address)
        values
        (#{username},#{birthday},#{sex},#{address})
    </insert>
</mapper>

UserMapper.xml

其中包含了if where sql  foreach  include 标签的使用,还有输出结果使用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">
<!-- namespace:命名空间,用于隔离sql -->
<!-- 还有一个很重要的作用,使用动态代理开发DAO,1. namespace必须和Mapper接口类路径一致 -->
<mapper namespace="com.test.mybatis.mapper.UserMapper">
    <!-- 根据用户id查询用户 -->
    <!-- 2. id必须和Mapper接口方法名一致 -->
    <!-- 3. parameterType必须和接口方法参数类型一致 -->
    <!-- 4. resultType必须和接口方法返回值类型一致 -->
    <select id="queryUserById" parameterType="Integer" resultType="user">
        select * from user where id = #{id}
    </select>
    <!-- 根据用户名查询用户 -->
    <select id="queryUserByUsername" parameterType="String" resultType="com.test.mybatis.pojo.User">
        select * from user where username like '%${value}%'
    </select>
    <!-- 保存用户 -->
    <insert id="saveUser" parameterType="com.test.mybatis.pojo.User">
        insert into user
        (username,birthday,sex,address)
        values
        (#{username},#{birthday},#{sex},#{address})
    </insert>
    
    <!-- 根据用户名模糊查询用户信息 -->
    <select id="queryUserByQueryVo" parameterType="com.test.mybatis.vo.QueryVo" 
            resultType="user">
        select * from user
        where 
        username
        like
        '%${user.username}%'
    </select>
    
    <!-- 查询用户表数据条数 -->
    <select id="countUser" resultType="Integer">
        select count(*)
        from user
    </select>
    
    <!-- 根据性别和名字查询用户   where 可以去掉第一个前And-->
    <select id="queryUserBySexAndUsername" parameterType="user" resultType="user">
        <!-- select * 
        from user -->
        <include refid="userAllFiledSelectStart"></include>
        <where>
            <if test="sex != null and sex != ''">
                and sex = #{sex}
            </if>
            <if test="username != null and username != ''">
                and username LIKE
                '%${username}%'
            </if>
        </where>
    </select>
    
    
    
    <sql id="userAllFiledSelectStart">
        select * from user
    </sql>
    
    <!-- 根据多个id查询用户信息    多个ID如 (1,2,3)
        public abstract List<User> queryUserByIdsFromArray(Integer[] ids);
     -->
     <select id="queryUserByIdsFromArray" parameterType="Integer" resultType="User">
         <include refid="userAllFiledSelectStart"></include>
         <where>
             id in
             <foreach collection="array" item="id" separator="," open="(" close=")">
                 #{id}
             </foreach>
         </where>
     </select>
    
    <!-- 
        根据多个id查询用户信息    多个ID如 (1,2,3)
        public abstract List<User> queryUserByIdsFromCollection(List<Integer> ids);
     -->
     <select id="queryUserByIdsFromCollection" parameterType="Integer" resultType="User">
         <include refid="userAllFiledSelectStart"></include>
         <where>
             <!-- foreach标签,进行遍历 -->
            <!-- collection:遍历的集合,这里是QueryVo的ids属性 -->
            <!-- item:遍历的项目,可以随便写,,但是和后面的#{}里面要一致 -->
            <!-- open:在前面添加的sql片段 -->
            <!-- close:在结尾处添加的sql片段 -->
            <!-- separator:指定遍历的元素之间使用的分隔符 -->
             <foreach collection="list" item="id" separator="," open="id in (" close=")">
                 #{id}
             </foreach>
         </where>
     </select>
     
    
    <!--
        根据多个id查询用户信息    多个ID如 (1,2,3)
        public abstract List<User> queryUserByIdsFromQueryVo(QueryVo vo);
      -->
    <select id="queryUserByIdsFromQueryVo" parameterType="com.test.mybatis.vo.QueryVo" resultType="User">
         <include refid="userAllFiledSelectStart"></include>
         <where>
             <foreach collection="idsList" item="id" separator="," open="id in (" close=")">
                 #{id}
             </foreach>
         </where>
     </select>
    
    
    <!-- resultMap最终还是要将结果映射到pojo上,type就是指定映射到哪一个pojo -->
    <!-- id:设置ResultMap的id -->
    <resultMap type="User" id="userResultMap">
        <!-- 定义主键 ,非常重要。如果是多个字段,则定义多个id -->
        <!-- property:主键在pojo中的属性名 -->
        <!-- column:主键在数据库中的列名 -->
        <id property="id" column="id"/>
    
        <!-- 定义普通属性 -->
        <result property="username" column="username"/>
        <result property="sex" column="sex"/>
        <result property="birthday" column="birthday"/>
        <result property="address" column="address"/>
        
        <!-- 配置一对多的关系
            collection :配置一对多属性
            property:User里面的orders属性名 
            javaType:属性类型 
            ofType:属性中的泛型的类型
            private Set<Orders> orders;
        -->
        <collection property="ordersList" javaType="java.util.List" ofType="Orders">
            <!-- 配置主键,表示oid是关联Order的唯一标识 -->
            <id property="id" column="oid"/>
        
            <!-- 定义普通属性 -->
            <result property="number" column="number" />
            <result property="createtime" column="createtime" />
            <result property="note" column="note" />
        </collection>
    </resultMap>
    
    
    <!-- 查询所有用户信息及用户关联的订单信息 -->
    <select id="queryAllUserInfoAssociationOrdersInfo" resultMap="userResultMap">
        SELECT
        u.id,
        u.username,
        u.birthday,
        u.sex,
        u.address,
        o.id oid,
        o.number,
        o.createtime,
        o.note
        FROM
        `user` u
        LEFT JOIN `orders` o ON u.id = o.user_id
    </select>
</mapper>

OrderMapper.xml

其中包含有一对一查询配置

<?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">
<!-- namespace:命名空间,用于隔离sql -->
<!-- 还有一个很重要的作用,使用动态代理开发DAO,1. namespace必须和Mapper接口类路径一致 -->
<mapper namespace="com.test.mybatis.mapper.OrderMapper">
    
    <!-- resultMap最终还是要将结果映射到pojo上,type就是指定映射到哪一个pojo -->
    <!-- id:设置ResultMap的id -->
    <resultMap type="Orders" id="orderResultMap">
        <!-- 定义主键 ,非常重要。如果是多个字段,则定义多个id -->
        <!-- property:主键在pojo中的属性名 -->
        <!-- column:主键在数据库中的列名 -->
        <!-- 
        <id property="id" column="id"/>
         -->
        
        <!-- 定义普通属性 -->
        <result property="userId" column="user_id"/>
        <!-- 
        
        <result property="number" column="number"/>
        <result property="createtime" column="createtime"/>
        <result property="note" column="note"/>
        
         -->
    </resultMap>
    
    <!-- 查询所有的订单数据 -->
    <select id="queryAllOrders" resultMap="orderResultMap">
        select * from orders
    </select>
    
    
    <!--
        方式一:使用resultType封装一个对应的类OrdersToUser
        询所有订单信息,关联查询下单用户信息
     -->
    <select id="queryAllOrdersAssociationUser1" resultType="OrdersToUser">
        select 
        o.id,
        o.user_id,
        o.number,
        o.createtime,
        o.note,
        u.username,
        u.address 
        from orders o 
        left join user  u on o.user_id = u.id;
    </select>
    
    <resultMap type="Orders" id="ordersMap">
        <id property="id" column="id"></id>
        <result property="userId" column="user_id"/>
        <result property="number" column="number"/>
        <result property="createtime" column="createtime"/>
        <result property="note" column="note"/>
        
        <!-- association :配置一对一属性 -->
        <!-- property:order里面的User属性名 -->
        <!-- javaType:属性类型 -->
        <association property="user" javaType="com.test.mybatis.pojo.User">
            <!-- id:声明主键,表示user_id是关联查询对象的唯一标识-->
            <id property="id" column="user_id" />
            <result property="username" column="username"/>
            <result property="address" column="address"/>
        </association>
    </resultMap>
    
    <!--
        方式二:使用resultMap,订单实体内部包含了用户属性
        //关联user,表达一对一的关系
        private User user;
        询所有订单信息,关联查询下单用户信息
     -->
     <!-- 一对一关联,查询订单,订单内部包含用户属性 -->
    <select id="queryAllOrdersAssociationUser2" resultMap="ordersMap">
        select 
        o.id,
        o.user_id,
        o.number,
        o.createtime,
        o.note,
        u.username,
        u.address 
        from orders o 
        left join user  u on o.user_id = u.id;
    </select>
</mapper>

MyBatis整合Spring--applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:aop="http://www.springframework.org/schema/aop" 
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context-4.0.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
                           http://www.springframework.org/schema/tx 
                           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                           http://www.springframework.org/schema/util 
                           http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    
    <!-- 1加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 2配置连接池 -->
    <bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>
    
    <!--3 配置SqlSessionFactory  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置mybatis核心配置文件 -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml" />
        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- 原始开发方式中,配置dao到spring中 -->
    <bean name="userDao" class="com.mybatis.spring.dao.impl.UserDaoImpl">
        <!-- 注入SqlSessionFatory -->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
    
    <!-- Mapper代理的方式开发方式一,配置Mapper代理对象 -->
    <bean name="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <!-- 配置mapper接口 -->
        <property name="mapperInterface" value="com.mybatis.spring.mapper.IUserMapper"></property>
        <!-- 配置sqlSessionFactory -->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
    
    <!-- Mapper代理的方式开发方式二,扫描包方式配置代理
        每个mapper代理对象的id就是类名,首字母小写。
        om.mybatis.spring.mapper下面就算还有子包,也会扫描到的。
     -->
     <!-- 
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.mybatis.spring.mapper"></property>
    </bean>
     -->
</beans>

 

 

原文地址:https://www.cnblogs.com/jepson6669/p/9021128.html