----------------------------

一、导入坐标
要想通过maven创建一个简单的mybatis项目,首先需要的是要导入相关的坐标。需要导入的坐标如下:


mysql mysql-connector-java 5.1.46 org.mybatis mybatis 3.5.6 junit junit 4.12 test 创建实体类User和在数据库中插入创建对应的user表。

二、配置mybatis的核心配置文件mybtis-config.xml
创建mybatis-config.xml的配置文件,用于配置连接数据库和注册Mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!--数据库连接的环境配置-->
<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="${driver}"/>
            <property name="url" value="${url}"/>
            <property name="username" value="${username}"/>
            <property name="password" value="${password}"/>
        </dataSource>
    </environment>
</environments>

<!--每一个Mapper.xml都需要在mybatis核心配置文件中注册-->
<mappers>
    <mapper resource="com/wkx/dao/UserMapper.xml"/>
</mappers>

①properties标签:可以动态配置属性。

可以全部在外部进行配置,如下:

也可以在通过property标签一部分在外部进行内部配置另一部分在内部进行配置(如下),增加配置的灵活性。 ②环境配置environments标签:用于配置数据的环境。可配置多个数据库环境,但是SqlSessionFactory只能选择一个去使用。如下: 可以在不同的环境下切换不同的数据环境,只需要修改environments标签中的default属性对应不同环境下的id属性,比如development和test不同的环境。

③映射器mappers:定义映射的路径,告诉mybatis去哪里找对应的语句。除了上述通过类路径的资源引用方式,也可以通过其它的方式。比如通过包的形式将映射器接口全部注册为映射器,如下:

问题:Mapper.xml的配置文件在mybatis核心配置文件注册时找不到对应Mapper.xml,是因为maven读取配置文件时只在resources的文件目录下寻找,所以需要在pom.xml文件中配置过滤器。所以pom.xml中应该添加如下代码:

src/main/resources **/*.properties **/*.xml true

<resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
    </resource>
</resources>

三、创建Mapper.xml 完成mybatis-config.xml配置文件的创建后,接着需要配置相关的Mapper.xml,进而进行SQL语句的编写。 select * from user

<!--使用User类作为输入类型-->
<update id="updateUser" parameterType="com.wkx.pojo.User">
    update user set name=#{name},pwd=#{pwd} where id=#{id}
</update>

<!--map类型(只需要其中的key对应sql语句中的需要注入的值)-->
<update id="updateUserMap" parameterType="map">
    update user set name=#{username} where id=#{uid}
</update>

①namespace命名空间:使用全限定类名对语句进行隔离,以及实现对接口的绑定。

②select、update等标签中的id属性对应的是Mapper接口中的方法名。通过id找到对应的方法需要执行的SQL语句。

③使用的Map集合类型对数据的SQL语句进行操作,只需要将Map集合中key对应SQL语句中的需要注入的值。也就是说SQL注入的值可以不和实体类中属性一致。同时,使用Map集合而不是User类作为传入类型进行传输时不需要将User类中所有数据传输。

四、编写工具类
mybatis的使用需要以SqlSessionFactory为核心,使用SqlSessionFactory去生产SqlSession对象。创建一个工具类去生产SqlSession对象,以后使用mybatis便可以从该工具类中拿出SqlSession。