zoukankan      html  css  js  c++  java
  • mybatis 的学习(一) 第一个mybatis 程序

    mybatis 的学习


    2. 第一个MyBatis程序

    ### 2.1创建数据库,并插入相关的数据
    
    CREATE TABLE `user_k` (
      `id` int(20) NOT NULL AUTO_INCREMENT,
      `name` varchar(30) DEFAULT NULL,
      `pwd` varchar(30) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
    
    ### 2.2	搭建环境
    

    2.2.1 新建一个普通的maven项目

    2.2.2删除src目录

    2.2.3 导入maven依赖

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.5</version>
    </dependency>
    
    

    2.3 创建一个模块

    2.3.1 编写一个mybaits-config.xml 的核心配置

    ​ 其中 mybatis-config.xml 的核心配置放置的位置是在resources目录下

    链接数据库需要一个db.properties文件

    driver=com.mysql.cj.jdbc.Driver
    username=root
    password=8020
    url=jdbc:mysql://localhost:8020/book?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    
    <?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"/>
    <!--配置相关内容 -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="logImpl" value="org.apache.ibatis.logging.stdout.StdOutImpl" />
    </settings>
    <!--给实体类起别名-->
    <typeAliases>
    <package name="com.qlx.pojo"/>
    </typeAliases>
    <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>
     <!--映射xxxMapper.xml-->
    <mappers>
    <mapper resource="com/qlx/mapper/UserMapper.xml"/>
    </mappers>
    </configuration>
    

    2.3.2 编写mybatis 工具类

    ​ 从 XML 中构建 SqlSessionFactory ,每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。

    从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。 但也可以使用任意的输入流(InputStream)实例,比如用文件路径字符串或 file:// URL 构造的输入流。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,使得从类路径或其它位置加载资源文件更加容易。

    官方给处获取 sqlSession的代码:

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

    我们可以写一个工具类,就不用每次都写一边这个代码

    public class MybatisUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static {
    try {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
    public static SqlSession getSqlSession() {
    // true   自动提交  
    return sqlSessionFactory.openSession(true);
    }
    }
    
    

    2.3.3 通过数据库编写实体类 这里我们通过使用lombok来生成get,set方法

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class UserK {
        private Integer id;
        private String name;
        private String pwd;
    }
    

    2.3.4 编写 mapper 接口

    public interface UserKMapper {
    
        /**
         * 添加一个用户
         *
         * @param userK
         * @return int
         * @author 小小的梦想丶
         * @date 2020/09/17 19:55:13
         */
        int addUser(UserK userK);
    
    }
    

    2.3.5 在mapper包下新建一个UserKMapper.xml

    ​ 在idea中连接数据库 会有更多的代码提示

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!--namespace 写的是mapper/dao 包下的xxxMapper接口-->
    <mapper namespace="com.qlx.mapper.UserKMapper">
    <insert id="addUser">
        insert into mybatis.user_k values (id=#{id,jdbcType=INTEGER},
        name=#{name,jdbcType=VARCHAR},pwd=#{pwd,jdbcType=VARCHAR})
    </insert>
    </mapper>
    

    2.3.6 测试 demo

    @Test
    public void testMyBatisUtils() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        UserKMapper mapper = sqlSession.getMapper(UserKMapper.class);
        //因为 id 在数据库设计的是自增 所以 这里写null
        UserK userK = new UserK(null, "haha", "haha");
        int i = mapper.addUser(userK);
        System.out.println(i);
    }
    

    结果如下:证明 这个工具类可用,并通过mybatis 进行一次数据的存储

    Opening JDBC Connection
    Created connection 1125736023.
    ==>  Preparing: insert into mybatis.user_k values (id=?, name=?,pwd=?)
    ==> Parameters: null, haha(String), haha(String)
    <==    Updates: 1
    1
    

    2.3.7 可能会出现的问题

    1. 配置文件没有进行绑定 写的UserKMapper.xml 需要在mybatis-config.xml中进行绑定

    2. 绑定接口的错误

    3. 方法名不对 可以在mybatis-config.xml中进行设置别名

    4. 返回类型

    5. maven 到处资源问题

      ​ maven 导出静态资源的问题可以在maven配置中添加下面的代码进行解决:

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

  • 相关阅读:
    [leetcode-135-Candy]
    [leetcode-151-Reverse Words in a String]
    [leetcode-139-Word Break]
    [leetcode-129-Sum Root to Leaf Numbers]
    [leetcode-143-Reorder List]
    [leetcode-141-Linked List Cycle]
    oracle 环境变量(中文显示乱码)
    Oracle 自增长id
    Spring.net 事件的注入
    Spirng.net 替换任意方法
  • 原文地址:https://www.cnblogs.com/lxsfve/p/13687447.html
Copyright © 2011-2022 走看看