mybatis的使用

1.如何使用mybatis

  • 创建user表,添加数据
  • 创建模块,导入坐标
  • 编写My Batis核心配置文件
  • 编写sql映射文件
  • 编码
    • 定义pojo类
    • 加载核心配置文件,获取SqlSessionFactory对象
    • 获取SqlSession对象,执行SQL语句
    • 释放资源

1.创建user表,添加数据

测试代码:

create database mybatis;
use mybatis;

drop table if exists tb_user;

create table tb_user(
                        id int primary key auto_increment,
                        username varchar(20),
                        password varchar(20),
                        gender char(1),
                        addr varchar(30)
);
INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '男', '北京');
INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');

2.创建模块,导入坐标[导入测试包时,还需要使用 logback.xml 配置文件]

<!--servlet-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
       <!-- 添加slf4j日志api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.20</version>
    </dependency>
    <!-- 添加logback-classic依赖 -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>
    <!-- 添加logback-core依赖 -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-core</artifactId>
        <version>1.2.3</version>
    </dependency>
    <!--mysql驱动-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.26</version>
        <scope>compile</scope>
    </dependency>
    <!--junit单元测试-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>
    <dependency>
    <!--mybatis-->
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>x.x.x</version>
</dependency>












    <!--logback.xml文件-->
    
    <?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--
        CONSOLE :表示当前的日志信息是可以输出到控制台的。
    -->
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%level] %blue(%d{HH:mm:ss.SSS}) %cyan([%thread]) %boldGreen(%logger{15}) - %msg %n</pattern>
        </encoder>
    </appender>

    <logger name="com.itheima" level="DEBUG" additivity="false">
        <appender-ref ref="Console"/>
    </logger>


    <!--

      level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
     , 默认debug
      <root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
      -->
    <root level="DEBUG">
        <appender-ref ref="Console"/>
    </root>
</configuration>

3.编写mybatis-config.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>
  <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>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

4. 编写sql映射文件userMapper.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:名称空间
-->

<mapper namespace="text">

    <select id="selectAll" resultType="com.itheima.pojo.User">
        select *
        from tb_user;
    </select>
    <select id="selectById" resultType="user">
        select *
        from tb_user where id = #{id};

    </select>
</mapper>

5. 编码

  • 定义pojo类

  • 加载核心配置文件,获取SqlSessionFactory对象

  • 获取SqlSession对象,执行SQL语句

  • 释放资源

    package com.itheima;
    import com.itheima.pojo.User;
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    /**
     * Mybatis 快速入门代码
     */
    public class MyBatisDemo {
    
        public static void main(String[] args) throws IOException {
    
            //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    
            //2. 获取SqlSession对象,用它来执行sql
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //3. 执行sql
            List<User> users = sqlSession.selectList("text.selectAll");  
            System.out.println(users);
            //4. 释放资源
            sqlSession.close();
    
        }
    }
    
    

优化代码使用Mapper代理(解决硬编码问题,简化后期sql代码)

  • 定义新建与sql映射文件同名的mapper接口,并将mapper接口和sql映射文件放置在同一目录下(**在resources下新建层级目录时使用com/user/mapper ” 斜杠 ” **)

  • 设置sql映射文件:mybatis-config.xmlnamespace属性为Mapper接口权限定名(小细节:后期如果有多个mapper文件,使用packing-name:com.bohai.mapper

    <!--        加载sql映射文件-->
            <mapper resource="com/itheima/mapper/UserMapper.xml"/>
    
    <!--Mapper代理方式-->
        <!--    <package name="com.itheima.mapper"/>-->
    
  • 在Mapper接口:large_blue_circle:中定义方法,方法名为SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致

    import com.itheima.pojo.User;
    
    import java.util.List;
    
    
    public interface UserMapper {
    
        List<User> selectAll();   //查询user对象的selectAll()方法
    
        User selectById(int id);
    
  • 编码

    • 通过sqlSession的getMapper方法获取Mapper接口的代理对象

      //3.1 获取UserMapper接口的代理对象
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
      
    • 调用对应的方法,完成sql执行

             List<User> users = userMapper.selectAll();
      
    • 完整代码:

      package com.itheima;
      
      
      import com.itheima.mapper.UserMapper;
      import com.itheima.pojo.User;
      import org.apache.ibatis.io.Resources;
      import org.apache.ibatis.session.SqlSession;
      import org.apache.ibatis.session.SqlSessionFactory;
      import org.apache.ibatis.session.SqlSessionFactoryBuilder;
      
      import java.io.IOException;
      import java.io.InputStream;
      import java.util.List;
      
      /**
       * Mybatis 代理开发
       */
      public class MyBatisDemo2 {
      
          public static void main(String[] args) throws IOException {
      
              //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
              String resource = "mybatis-config.xml";
              InputStream inputStream = Resources.getResourceAsStream(resource);
              SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      
              //2. 获取SqlSession对象,用它来执行sql
              SqlSession sqlSession = sqlSessionFactory.openSession();
      
              //3. 获取UserMapper接口的代理对象
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
              List<User> users = userMapper.selectAll();
      
              System.out.println(users);
              //4. 释放资源
              sqlSession.close();
      
          }
      }
      
      
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容