Mybatis配置文件

一、映射文件

1.#{}和${}的区别

 #{}:Sql语句使用占位符预编译,可以防止Sql注入

 ${}:Sql语句使用字符串拼接,无法防止Sql注入

2.映射文件中语句标签的参数

 1.id属性:

  映射文件对应的接口中的方法名

 2.parameterType:

  参数类型,可以是基本类型,也可以是实体类。当类型是基本类型且只有一个的时候,Sql语句只需要一个占位符,参数名可随意,如select * from user where id=#{随意参数名}

 3.resultType:

  返回类型,可以是基本类型,也可以是实体类。实体类中的属性名必须和数据库中表的字段名一一对应,否则无法完成封装。当不对应的时候,可以采取查询时取别名或resultMap进行封装

 4.resultMap:

  返回值列表

<resultMap id="userMap" type="com.itheima.domain.UserTest">
    <!--property对应实体类的属性名,,column对应表的字段名-->
    <result property="userName" column="username"></result>
    <result property="userId" column="id"></result>
    <result property="userAddress" column="address"></result>
    <result property="userSex" column="sex"></result>
    <result property="userBirthday" column="brithday"></result>
</resultMap>
<!--resultMap的值为上面 resultMap标签的id-->
<select id="findAllTest" resultMap="userMap">
    select * from user;
</select>

3.保存用户并返回自动生成的id,id会自动设置给传过来的实体类

<!-- 保存用户并返回自动生成的id,id会自动设置给传过来的实体类 -->
    <insert id="saveUser" parameterType="com.itheima.domain.User">
        <selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="int">
            <!--keyProperty实体类的属性名,keyColumn数据库表的列名,order保存之前还是之后-->
            select last_insert_id();
        </selectKey>
        insert into user(username,birthday,sex,address)
        values(#{username},#{birthday},#{sex},#{address});
  </insert>

4.动态Sql

 1.if标签

<!--动态Sql-if标签,注意多条件的时候用and-->
<select id="findByUser" resultType="com.itheima.domain.User" parameterType="com.itheima.domain.User">
        select * from user where 1=1
        <if test="username!=null">
            and username=#{username}
        </if>
        <if test="sex!=null and address!=null">
            and sex=#{sex} and address=#{address}
        </if>
    </select>

 2.where标签,可以省略where 1=1

<!--动态Sql-where标签-->
    <select id="findByUser" resultType="com.itheima.domain.User" parameterType="com.itheima.domain.User">
        select * from user
        <where>
            <if test="username!=null">
                and username=#{username}
            </if>
            <if test="sex!=null and address!=null">
                and sex=#{sex} and address=#{address}
            </if>
        </where>
    </select> 

 3.for标签

<!--动态Sql-foreach标签-->
    <select id="findByIds" parameterType="com.itheima.domain.UserTest" resultType="com.itheima.domain.User">
        select * from user
        <where>
            <foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
                #{id}
            </foreach>
        </where>
    </select>

 4.配置通用Sql

<sql id="defaultSql">
        <!--注意后面不要加分号-->
        select * from user
    </sql>
    <select id="findByList" parameterType="List" resultType="com.itheima.domain.User">
        <!--使用默认Sql-->
        <include refid="defaultSql"></include>
        <where>
            <foreach collection="list" open="and id in (" close=")" item="id" separator=",">
                #{id}
            </foreach>
        </where>
    </select>

  

二、核心配置文件

1.配置别名

<!--配置typeAliases
        配置别名:配置后别名不区分大小写
    -->
    <typeAliases>
        <!--配置一个实体类的别名-->
        <!--<typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>-->

        <!--配置一个包下所有实体类的别名,类名就是别名-->
        <package name="com.itheima.domain"></package>
    </typeAliases>

2.配置properties

<!--配置properties
        可以在标签内配置属性,也可以通过resource引用外部文件jbdc.properties
        resource属性:用于指定配置文件的位置,是按照类路径的写法来写的,配置文件必须在类路径下
    -->
    <properties resource="jdbc.properties">
        <!--<property name="driver" value="com.mysql.jdbc.Driver"/>-->
        <!--<property name="url" value="jdbc:mysql://localhost:3306/mybatis_study?characterEncoding=UTF-8"/>-->
        <!--<property name="username" value="root"/>-->
        <!--<property name="password" value="2013.71123"/>-->
    </properties>

    <!--配置typeAliases
        配置别名:配置后别名不区分大小写
    -->
    <typeAliases>
        <!--配置一个实体类的别名-->
        <!--<typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>-->

        <!--配置一个包下所有实体类的别名,类名就是别名-->
        <package name="com.itheima.domain"></package>
    </typeAliases>
    <!--配置环境-->
    <environments default="mysql">
        <!--配置Mysql的环境,id和default必须相同-->
        <environment id="mysql">
            <!--配置事务类型-->
            <transactionManager type="JDBC"></transactionManager>

            <!--配置数据源(也叫连接池)
                type属性:采用何种连接池方式
            -->
            <dataSource type="POOLED">
                <!--配置连接数据库的4个基本信息-->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>

    </environments>

3.配置mapper

<!--配置映射文件目录:xml方式-->
    <mappers>
        <!--<mapper resource="com/itheima/dao/IUserMapper.xml"></mapper>-->
        <package name="com.itheima.dao"></package>
    </mappers>
    <!--配置映射文件目录:注解方式  全限定类名
        使用注解方式就不需要IUserMapper.xml配置文件了
    -->
    <!--<mappers>-->
        <!--<mapper class="com.itheima.dao.IUserDao"></mapper>-->
    <!--</mappers>-->

 4.使用JDNI数据源

 在web项目中的MATE-INF下新建一个context.xml,内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<Context>
    <Resource
        name="jdbc/mybatis_study"
        type="javax.sql.DataSource"
        auth="Container"
        maxActive="20"
        maxWait="10000"
        maxIdle="5"
        username="root"
        password="2013.71123"
        driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/mybatis_study"
    ></Resource>

</Context>

 核心配置文件中配置数据源的时候,使用以下方式:

<!--配置环境-->
    <environments default="mysql">
        <!--配置Mysql的环境,id和default必须相同-->
        <environment id="mysql">
            <!--配置事务类型-->
            <transactionManager type="JDBC"></transactionManager>

            <!--配置数据源(也叫连接池)
                type属性:采用何种连接池方式
            -->
            <dataSource type="JNDI">
                <property name="data_source" value="java:comp/env/jdbc/mybatis_study"/>
               <!-- <property name="driver" value="com.mysql.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_study"></property>
                <property name="username" value="root"></property>
                <property name="password" value="2013.71123"></property>-->
            </dataSource>
        </environment>

    </environments>

 配置完成后启动tomcat服务器,执行以下jsp文件:

<%@ page import="java.io.InputStream" %>
<%@ page import="org.apache.ibatis.session.SqlSession" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactoryBuilder" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactory" %>
<%@ page import="java.util.List" %>
<%@ page import="org.apache.ibatis.io.Resources" %>
<%@ page import="com.itheima.domain.Role" %>
<%@ page import="com.itheima.dao.IRoleDao" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<h2>Hello World!</h2>
<%
    InputStream in=Resources.getResourceAsStream("SqlMapConfigs.xml");
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
    SqlSession sqlSession=sessionFactory.openSession();
    IRoleDao roleDao=sqlSession.getMapper(IRoleDao.class);
    List<Role> all = roleDao.findAll();
    for(Role role : all) {
        System.out.println(role);
        System.out.println(role.getUsers());
        System.out.println("-----------------");
    }
    in.close();
    sqlSession.close();

%>
</body>
</html>
原文地址:https://www.cnblogs.com/zy-Luo/p/11708220.html