Mybatis环境配置

Mybatis环境配置

官方文档地址:https://mybatis.org/mybatis-3/zh/getting-started.html

一.添加依赖

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>

二.构建SqlSessionFactory

首先,我们通过xml文件构建SqlSessionFactory,查看官方文档:

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

所以,这里我们建立一个名为mybatis-config.xml的文件并且放在resources目录下,并依照官方文档进行配置

<?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>
    <typeAliases>
        <package name="com.guan.bean"/>
    </typeAliases>
    <!--this is a develop enviroment-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/dailyClick-test?useSSL=false&amp;useUnicode=false&amp;characterEncoding=UTF-8"/>
                <property name="username" value="username"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    <!--every mappper should register here -->
    <mappers>
<!--        <package name="com.guan.dao"/>-->
        <mapper resource="com/guan/dao/UserMapper.xml"/>
    </mappers>
</configuration>

几个需要注意的地方

  1. xml文件中不要出现中文注释(包括在整个项目中出现过的其它xml文件)
  2. useSSL=false
  3. &amp;等同于普通yaml配置文件中&

三.写好配置文件后,我们可以写一个用于连接的工具类来获得sqlSession对象了

注:

这里使用了一个静态代码块,Java静态代码块的作用:Java静态代码块中的代码会在类加载JVM时运行,且只被执行一次,也就是说这些代码不需要实例化类就能够被调用。一般情况下,如果有些代码必须在项目启动的时候就执行的时候,就需要使用静态代码块。

static{
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();  //注意这里返回的sqlSession才是真正的操作对象
    }

四.编写数据库的基本操作(DAO/mapper)

  1. 让我们先写好一个接口

注:这里的UserBean是我自己写的,里面的每一个属性都对对应了数据库user表中的字段名

public interface UserDAO {
    List<UserBean> getUserList();
}
  1. 通过在改接口的同一个目录下新建一个.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">
<!--bind to a interface-->
<mapper namespace="com.guan.dao.UserDAO" >
<!--    here should the select should bind to a function-->
  <select id="getUserList" resultType="com.guan.bean.UserBean">
    select * from user
  </select>
</mapper>

解释一下这里的几个重要属性:
(1). namespace:空间命名,也就是接口的具体位置
(2). id是绑定的接口
(3). resultType是返回类型,这里要写全地址

3.在mybatis-config.xml中对mapper进行注册

<mappers>
     <mapper resource="com/guan/dao/UserMapper.xml"/>
</mappers>

五.测试...前的最后一个问题

如果你在此时进行测试,通常会出现以下报错:

Exception in thread "main" java.lang.ExceptionInInitializerError

打开打包后的dist文件下的DAO层,你会发现里面只有userDAO接口而没有相应的.xml配置文件,这是因为maven的资源过滤问题.
为此,我们还需要对pom.xml进行配置

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

6.关于编写增删改查的配置

<mapper namespace="com.guan.dao.UserDAO" >
<!--    here should the select should bind to a function-->
  <select id="getUserList" resultType="com.guan.bean.UserBean">
    select * from user
  </select>

  <insert id="insertUser" parameterType="com.guan.bean.UserBean">
    INSERT INTO user(UId,UName,USet,UAuth,UPassword,UState) VALUES(#{UId},#{UName},#{USet},#{UAuth},#{UPassword},#{UState})
  </insert>

  <update id="updateUserById" parameterType="com.guan.bean.UserBean">
    UPDATE user SET USet = #{USet} WHERE UId = #{UId};
  </update>

  <delete id="deleteById" parameterType="java.lang.String">
    DELETE FROM user WHERE UId = #{id};
  </delete>
</mapper>

注意:

  1. 增删改查都有自己对应的标签
  2. 如果有参数,#{xxXxx}中放的就是参数
  3. Mybatis对于数据库改变的操作都必须要主动用事务提交,否则失效
  4. 记得SqlSession和Connection一样都是需要主动关闭的
  5. 关于模糊查询,在java代码执行的时候,传递通配符%...%(这样做可以防止sql注入,原理应该也是类似preparedStatement,在实际的使用中是将"做了转义处理,类似/",使"仅仅是作为字符串的一部分)
    恭喜,到这里配置已经基本完成了!

7.测试

public static void Maintest(){
    SqlSession sqlSession = Connection.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class); //注意这里获得的是**接口的DAO对象**
    List<UserBean> userBeans = userMapper.queryById("3180421016");
    System.out.println(userBeans);
    sqlSession.close();
}
posted @ 2020-07-21 19:59  Arno_vc  阅读(191)  评论(0编辑  收藏  举报